package com.yuanfeng.order.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.dto.PageUserTokenBeanDTO;
import com.yuanfeng.commoms.dto.base.BaseExpressDTO;
import com.yuanfeng.commoms.dto.base.MemberMessageListIntegralDTO;
import com.yuanfeng.commoms.dto.goods.ReceiveGoodsDetailsDTO;
import com.yuanfeng.commoms.dto.order.AddInventoryDTO;
import com.yuanfeng.commoms.dto.order.PlatFormMemberSelfQueryDTO;
import com.yuanfeng.commoms.dto.order.WapGoodsSaleSumDTO;
import com.yuanfeng.commoms.dto.shop.ShopContractDTO;
import com.yuanfeng.commoms.dto.userms.BusinessUserInfoDTO;
import com.yuanfeng.commoms.dto.userms.PlusEquityDTO;
import com.yuanfeng.commoms.dto.userms.UserInfoDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.rocketmq.MqSendUtils;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.util.Json.JSONSerializer;
import com.yuanfeng.commoms.util.Json.JsonUtils;
import com.yuanfeng.commoms.util.excel.ExcelsUtil;
import com.yuanfeng.commoms.util.kuaidiniao.KdniaoSubscribeAPI;
import com.yuanfeng.commoms.util.kuaidiniao.KdniaoTrackQueryAPI;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.base.BaseDistrictVO;
import com.yuanfeng.commoms.vo.base.KdniaoExpressVO;
import com.yuanfeng.commoms.vo.fx.GoodsVkSetVO;
import com.yuanfeng.commoms.vo.goods.GoodsDetailsListVO;
import com.yuanfeng.commoms.vo.job.AcquiescenceVO;
import com.yuanfeng.commoms.vo.order.*;
import com.yuanfeng.commoms.vo.shop.ShopMemberVO;
import com.yuanfeng.commoms.vo.shop.ShopShippingAddressVO;
import com.yuanfeng.commoms.vo.shop.ShopdpexpressVO;
import com.yuanfeng.commoms.vo.shop.ShopkdniaoVO;
import com.yuanfeng.commoms.vo.user.UserInfoOrderDetailVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.order.dto.*;
import com.yuanfeng.order.entity.*;
import com.yuanfeng.order.feign.*;
import com.yuanfeng.order.mapper.*;
import com.yuanfeng.order.service.FXService;
import com.yuanfeng.order.service.OrderApprovalService;
import com.yuanfeng.order.service.OrderBaseService;
import com.yuanfeng.order.utils.FxThread;
import com.yuanfeng.order.utils.PageInfo;
import com.yuanfeng.order.utils.SensitiveWord;
import com.yuanfeng.order.vo.*;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.TransactionManagerHolder;
import io.seata.tm.api.GlobalTransactionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.yuanfeng.commoms.util.TokenUtils.checkToken;

/**
 * @ClassName OrderBaseServiceImpl
 * @Description 订单详细信息
 * @Author cyp
 * @Date 2023-06-06 15:00:49
 * @Version 1.0
 **/
@Service
public class OrderBaseServiceImpl extends ServiceImpl<OrderBaseMapper, OrderBaseEntity>
        implements OrderBaseService {

    @Resource
    private OrderGoodsMapper orderGoodsMapper;
    @Resource
    private OrderCommissionMapper orderCommissionMapper;
    @Resource
    private OrderReturnMapper orderReturnMapper;
    @Resource
    private OrderGoodsEvaluationMapper orderGoodsEvaluationMapper;
    @Resource
    private OrderInvoiceInfoMapper orderInvoiceInfoMapper;
    @Autowired
    private OrderApprovalService orderApprovalService;
    @Autowired
    private ActivityServiceClient activityServiceClient;
    @Autowired
    private GoodServiceClient goodServiceClient;
    @Autowired
    private PayMentServiceClient payMentServiceClient;
    @Autowired
    private UserServiceClient userServiceClient;
    @Autowired
    private BaseServiceClient baseServiceClient;
    @Autowired
    private BusinessServiceClient businessServiceClient;

    @Autowired
    private ThirdPartyServiceClient thirdPartyServiceClient;
    @Autowired
    private FXService fxService;
    @Resource
    private OrderBaseMapper orderBaseMapper;
    @Resource
    private OrderPaymentVocherMapper orderPaymentVocherMapper;

    final Logger log = LoggerFactory.getLogger(OrderBaseServiceImpl.class);

    @Override
    public ResponseResult queryAmountPaid(Map<String, String> map) {
        PayDetailsVO payDetails = null;
        BigDecimal paymentAmount = new BigDecimal(0);
        String paymentNumber = null;
        try {
            paymentNumber = map.get("paymentNumber");
            if (StringUtils.isEmpty(paymentNumber)) {
                return null;
            }
            String substring = paymentNumber.substring(0, 1);
            if ("U".equals(substring)) {
                payDetails = this.baseMapper.querypaymentAmount(paymentNumber);
            } else {
                payDetails = this.baseMapper.querypaymentByOrder(paymentNumber);
            }
            //查询订单待支付时间
            Long orderCancelTime = queryOrderCancelTime(map);
            payDetails.setOrderCancelTime(orderCancelTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success(payDetails);
    }

    private Long queryOrderCancelTime(Map<String, String> map) {
        Long retoverplusTime = null;
        String orderId = String.valueOf(map.get("orderId"));
        //根据orderId查询订单
        OrderListVO orderList = this.baseMapper.queryOrderCreateTime(orderId);
        Integer status = orderList.getOrderStatus();
        List<GoodsDetailsListVO> goodsDetailsList = this.baseMapper.queryGoodsList(orderId);
        // 商品总价
        BigDecimal paymentPrice = new BigDecimal(0);
        for (int j = 0; j < goodsDetailsList.size(); j++) {
            //若为待付款订单，对限时秒杀商品添加距离付款时间
            if (1 == status) {
                Integer goodsId = goodsDetailsList.get(j).getGoodsId();
                Integer seckillId = this.baseMapper.queryCountForSeckillGoods(goodsId);
                if (null != seckillId && seckillId > 0) {
                    //取消时间 单位分钟
                    Integer cancelTime = this.baseMapper.queryCancelTime(seckillId);
                    if (null != cancelTime && cancelTime > 0) {
//                        String orderCreateTime = orderList.getOrderCreateTime();
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        try {
                            Date orderCreateTimeDate = orderList.getOrderCreateTime();
                            Calendar cal = Calendar.getInstance();
                            cal.setTime(orderCreateTimeDate);
                            cal.add(Calendar.MINUTE, cancelTime);
                            Date orderCancelTime = cal.getTime();
                            if (new Date().before(orderCancelTime)) {
                                Long overplusTime = orderCancelTime.getTime();
                                if (retoverplusTime == null) {
                                    retoverplusTime = overplusTime;
                                } else if (retoverplusTime > overplusTime) {
                                    retoverplusTime = overplusTime;
                                }
                            }
                        } catch (Exception e) {
                        }

                    }
                }
            }
        }
        return retoverplusTime;
    }

    @Override
    public ResponseResult queryintegraOrdersCount(Map<String, Object> map) {
        Integer count = this.baseMapper.queryintegraOrdersCount(map.get("userId").toString());
        return ResponseResult.success(count);
    }

    @Override
    public Integer queryShopIdByOrderIdNum(Map<String, Object> map) {
        Integer shopIdCount = this.baseMapper.selectCount(new LambdaQueryWrapper<OrderBaseEntity>()
                .eq(OrderBaseEntity::getOrderId, map.get("orderId")).or().eq(OrderBaseEntity::getPaymentNumber, map.get("orderId"))
                .last("limit 1"));
        return shopIdCount;
    }

    @Override
    public ResponseResult queryShopIdByOrderInfo(Map<String, Object> map) {
        OrderBaseEntity entity = this.baseMapper.selectOne(new LambdaQueryWrapper<OrderBaseEntity>()
                .eq(OrderBaseEntity::getOrderId, map.get("orderId")).or().eq(OrderBaseEntity::getPaymentNumber, map.get("orderId"))
                .last("limit 1"));
        return ResponseResult.success(entity);
    }

    @Override
    public Integer queryGoodNumByOrderId(Map<String, Object> map) {
        Integer num = this.baseMapper.queryGoodNumByOrderId(map.get("orderId").toString());
        return num;
    }

    @Override
    public ResponseResult messageToRemind(Map<Object, Object> map) {
        String token = (String) map.get("token");
        boolean isExist = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (isExist) {
            // 获取user信息
            String userinfo = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + token);
            UserInfoDTO ui = JSON.parseObject(userinfo, UserInfoDTO.class);
            UserInfoVO userInfo = ui.getUser();
            String userId = userInfo.getUserId();
            MessageRemindNumVO mrn = this.baseMapper.selectOrderBaseNum(userId);

            if (null != mrn) {
                Map returnMap = this.baseMapper.selectOrderReturnNum(userId);
                if (returnMap != null) {
                    int afterSales = Integer.parseInt(returnMap.get("afterSales").toString());
                    int returnNum = Integer.parseInt(returnMap.get("returnNum").toString());
                    int refundNum = Integer.parseInt(returnMap.get("refundNum").toString());
                    mrn.setRefundAndAfterSale(afterSales - returnNum - refundNum);
                }

            }


            return ResponseResult.success(mrn);
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
    }

    @Override
    public ResponseResult deleteOrder(Map<String, Object> map) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());

        String userId = userInfo.getUserId();
        String orderId = (String) map.get("orderId");
        userId = map.get("userId") == null ? userId : (String) map.get("userId");

        OrderBaseEntity orderBaseEntity = this.baseMapper.selectById(orderId);
        Integer orderStatus = orderBaseEntity.getOrderStatus();
        // 判断订单
        if (orderStatus == 1 || orderStatus == 6 || orderStatus == 7 || orderStatus == 9) {
            int flag = orderGoodsMapper.update(null, new LambdaUpdateWrapper<OrderGoodsEntity>()
                    .eq(OrderGoodsEntity::getBuyerUserId, userId)
                    .eq(OrderGoodsEntity::getOrderId, orderId)
                    .set(OrderGoodsEntity::getOrderDel, 1));

            boolean isDelete = flag == CommonStatusEnum.SUCCESS.getCode();
            if (isDelete) {
                this.baseMapper.update(null, new LambdaUpdateWrapper<OrderBaseEntity>()
                        .eq(OrderBaseEntity::getBuyerUserId, userId)
                        .eq(OrderBaseEntity::getOrderId, orderId)
                        .set(OrderBaseEntity::getOrderDel, 1));

                return ResponseResult.success();
            } else {
                return ResponseResult.fail();
            }
        }
        return ResponseResult.success();
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult cancelTheOrder(Map<Object, Object> map) throws TransactionException {
        try {
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());
            String userId = map.get("userId") != null ? (String) map.get("userId") : userInfo.getUserId();
            String orderid = map.get("orderId").toString();
            // 订单取消者身份
            Integer orderCancelIdentity = Integer.valueOf(map.get("orderCancelIdentity").toString());
            // 1：买家
            // 2：卖家
            // 3：系统
            List<String> orderIdList = new ArrayList<>();
            orderIdList.add(orderid);
            // 爆品取消时需求跟绑定商品一起取消
            OrderBaseEntity orderPayInfo = this.baseMapper.selectById(orderid);

            if (orderPayInfo.getOrderType().intValue() == CommonType.orderType.HOT_GOODS_TYPE.getCode()) {
                List<OrderBaseEntity> orderPayInfoList = this.baseMapper.selectList(new LambdaQueryWrapper<OrderBaseEntity>()
                        .eq(OrderBaseEntity::getPaymentNumber, orderPayInfo.getPaymentNumber()));
                orderIdList = orderPayInfoList.stream().map(OrderBaseEntity::getOrderId).collect(Collectors.toList());
            }

            for (String orderId : orderIdList) {
                // 订单取消状态
                Integer orderStatus = CommonType.orderStatus.CANCEL.getCode();
                OrderBaseEntity orderBaseEntity = this.baseMapper.selectOne(new LambdaQueryWrapper<OrderBaseEntity>()
                        .eq(OrderBaseEntity::getBuyerUserId, userId).eq(OrderBaseEntity::getOrderId, orderId));
                // 查询该订单是否已取消
                Integer status = orderBaseEntity.getOrderStatus();
                if (orderStatus.equals(status)) {
                    //该订单已取消，请勿重复操作！
                    return ResponseResult.fail(BizCodeEnume.ORDER_CANCELED);

                } else {
                    //获取非数字订单
                    OrderBaseEntity order = this.baseMapper.selectById(orderid);
                    String record_payorder = order.getPaymentNumber();
                    //取消订单 删除当前用户的拼团信息
                    Map<String, Object> pinTuanMap = new HashMap<>();
                    pinTuanMap.put("orderId", record_payorder);
                    activityServiceClient.deletePinTuanInfo(pinTuanMap);

//                    WapGoodsSaleSumDTO wgssu = new WapGoodsSaleSumDTO();
//                    Integer goodsType = 0;
                    List goodsId = new ArrayList();
                    // 查询商品信息中商品id,商品数量
                    List<AddInventoryDTO> aie = this.baseMapper.queryGoodsDetails(orderId);
                    for (AddInventoryDTO addInventoryDTO : aie) {
                        goodsId.add(addInventoryDTO.getGoodsId());
//                        wgssu.setToken(map.get("token").toString());
//                        wgssu.setGoodsId(aie.get(i).getGoodsId());
//                        wgssu.setCommonId(aie.get(i).getCommonId());
//                        wgssu.setGoodsNum(aie.get(i).getOrderGoodsNum().toString());
//                        wgssu.setTreasureOrderShopId(aie.get(i).getTreasureOrderShopId());
//                        if (aie.get(i).getOrderPromotionId() == 6) {
//                            goodsType = 1;
//                        }
//                        wgssu.setGoodsType(goodsType);
//                        ResponseResult result = goodServiceClient.updateStockReduce(wgssu);
                    }
                    // 订单取消原因
                    String orderCancelReason = (String) map.get("orderCancelReason");
                    // 订单取消时间
                    Date orderCancelDate = DateUtils.getNowDate();

                    boolean isUpdateSuccess = this.baseMapper.update(null, new LambdaUpdateWrapper<OrderBaseEntity>()
                            .eq(OrderBaseEntity::getOrderId, orderPayInfo.getOrderId())
                            .set(OrderBaseEntity::getOrderStatus, orderStatus)
                            .set(OrderBaseEntity::getOrderCancelIdentity, orderCancelIdentity)
                            .set(OrderBaseEntity::getOrderCancelReason, orderCancelReason)
                            .set(OrderBaseEntity::getOrderCancelDate, orderCancelDate)) == CommonStatusEnum.SUCCESS.getCode();

                    boolean isUpdateGoodsSuccess = orderGoodsMapper.update(null, new LambdaUpdateWrapper<OrderGoodsEntity>()
                            .eq(OrderGoodsEntity::getBuyerUserId, userId)
                            .eq(OrderGoodsEntity::getOrderId, orderId)
                            .set(OrderGoodsEntity::getOrderGoodsStatus, orderStatus)) == CommonStatusEnum.SUCCESS.getCode();

                    //取消佣金订单
                    orderCommissionMapper.update(null, new LambdaUpdateWrapper<OrderCommissionEntity>()
                            .eq(OrderCommissionEntity::getOrderId, orderId)
                            .set(OrderCommissionEntity::getOrderStatus, CommonType.CommissionOrderStatus.CANCEL.getCode()));

                    //取消付款状态
                    payMentServiceClient.updateCancelStatus(orderId);
                    //退还plus会员折扣
                    plusdis(orderId,userId,goodsId);
                }
                // 查询支付单号
                String payMentNumber = orderPayInfo.getPaymentNumber();
                String redpacketId = orderPayInfo.getRedpacketCode();
                String voucherCode = orderPayInfo.getVoucherCode();
                String platformCouponCode = orderPayInfo.getPlatformCouponCode();
                String markId = orderPayInfo.getOrderBuyId();
                if (markId != null) {
                    Map<Object, Object> ptMap = new HashMap<>();
                    ptMap.put("userId", userId);
                    ptMap.put("markId", markId);
                    //修改拼团信息
                    activityServiceClient.updatePinttuan(ptMap);
                }
                //取消订单成功后 修改库存
                //获取goodsid commonid 购买数量
                List<OrderGoodsEntity> orderGoodsEntityList = orderGoodsMapper.selectList(new LambdaQueryWrapper<OrderGoodsEntity>()
                        .eq(OrderGoodsEntity::getOrderId, orderId));
                //封装数据
                List<WapGoodsSaleSumDTO> wapGood = new ArrayList<>();
                if (CollectionUtils.isNotEmpty(orderGoodsEntityList)) {
                    wapGood = orderGoodsEntityList.stream().map(entity -> {
                        WapGoodsSaleSumDTO catResult = new WapGoodsSaleSumDTO();
                        catResult.setGoodsNum(entity.getOrderGoodsNum());
                        BeanUtils.copyProperties(entity, catResult);
                        return catResult;
                    }).collect(Collectors.toList());
                }

                //修改商品库存
                goodServiceClient.updateGoodsStock(wapGood);
                //退还红包
                if (redpacketId != null) {
                    // 查询订单状态
                    List<Integer> orderStatusList = this.baseMapper.selectList(new LambdaQueryWrapper<OrderBaseEntity>()
                            .eq(OrderBaseEntity::getPaymentNumber, payMentNumber))
                            .stream().map(OrderBaseEntity::getOrderStatus).collect(Collectors.toList());
                    Map<String, Object> codeMap = new HashMap<String, Object>();
                    codeMap.put("redpacketId", redpacketId);
                    codeMap.put("platformVoucherCode", platformCouponCode);
                    codeMap.put("type", "0");
                    Set set = new HashSet(orderStatusList);
                    if (set.size() == 1) {
                        activityServiceClient.updateSalesPrm(codeMap);
                        if (voucherCode != null) {
                            List<String> voucherCodeList = Arrays.asList(voucherCode.split(","));
                            Map<String, Object> voucherCodeMap = new HashMap<String, Object>();
                            voucherCodeMap.put("voucherId", voucherCodeList);
                            voucherCodeMap.put("type", "0");
                            activityServiceClient.updateSalesPrm(voucherCodeMap);
                        }
                    }
                } else {
                    if (org.apache.commons.lang.StringUtils.isNotBlank(voucherCode)) {
                        List<String> voucherCodeList = Arrays.asList(voucherCode.split(","));
                        Map<String, Object> voucherCodeMap = new HashMap<String, Object>();
                        voucherCodeMap.put("voucherId", voucherCodeList);
                        voucherCodeMap.put("platformVoucherCode", platformCouponCode);
                        voucherCodeMap.put("type", "0");
                        activityServiceClient.updateSalesPrm(voucherCodeMap);
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            // 回滚
            GlobalTransactionContext.reload(RootContext.getXID()).rollback();
            return ResponseResult.fail(e.getMessage());
        }
        return ResponseResult.success();
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult confirmTheGoods(Map<Object, Object> map) throws TransactionException {
        ResponseResult result = new ResponseResult();
        String token = (String) map.get("token");
        boolean isExist = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (isExist) {
            try {
                // String转object
                UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
                if (ui == null) {
                    return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
                }
                String userId = map.get("userId") == null ? ui.getUserId() : map.get("userId").toString();
                String orderId = (String) map.get("orderId");
                //订单信息
                OrderBaseEntity orderBaseEntity = this.baseMapper.selectOne(new LambdaQueryWrapper<OrderBaseEntity>()
                        .eq(OrderBaseEntity::getBuyerUserId, userId).eq(OrderBaseEntity::getOrderId, orderId));

                Date orderFinishedTime = DateUtils.getNowDate();
                Integer orderStatus = CommonType.orderStatus.CONFIRM_RECEIPT.getCode();
                // 获取最晚收货时间
                Integer orderReceiverDate = DateUtils.timeToStamp(orderBaseEntity.getOrderReceiverDate());
                // 获取当前时间
                Integer dateTime = DateUtils.timeToStamp();
                // 订单金额
                String sellerId = orderBaseEntity.getSellerUserId();
                BigDecimal money = orderBaseEntity.getOrderPaymentAmount();
                Map<String, Object> moneyMap = new HashMap<>();
                moneyMap.put("sellerId", sellerId);
                moneyMap.put("money", money);

                String sellerMobile = orderBaseEntity.getOrderSellerContact();
                // 判断最晚收货时间与当前时间
                if (dateTime.equals(orderReceiverDate) || dateTime > orderReceiverDate) {
                    //默认收货时间(goods)
                    boolean isSuccessByGoodsForUpdate = this.baseMapper.updateByOrderGoodsForDefaultFinish(orderId, orderStatus);
                    boolean isSuccessByBaseForUpdate = this.baseMapper.updateByOrderBaseForDefaultFinish(orderId, orderStatus);
                    if (isSuccessByGoodsForUpdate && isSuccessByBaseForUpdate) {
                        //计算售后最后时间
                        Calendar instance = Calendar.getInstance();
                        instance.setTime(orderBaseEntity.getOrderReceiverDate());
                        instance.add(Calendar.DATE, 14);
                        Date orderLastReturnTime = instance.getTime();
                        //更新订单最后售后时间
                        this.baseMapper.updateByOrderBaseorderLastReturnTime(orderId, orderLastReturnTime);
                        result.setCode(CommonStatusEnum.SUCCESS.getCode());
                        result.setMessage(BizCodeEnume.DEFAULT_RECEIPT_SUCCEEDED.getMsg());

                    } else {
                        result.setCode(CommonStatusEnum.FAIL.getCode());
                        result.setMessage(BizCodeEnume.DEFAULT_RECEIPT_FAILED.getMsg());
                    }
                } else {
                    boolean isSuccessByGoodsForUpdate = orderGoodsMapper.update(null, new LambdaUpdateWrapper<OrderGoodsEntity>()
                            .eq(OrderGoodsEntity::getOrderId, orderId)
                            .set(OrderGoodsEntity::getOrderGoodsStatus, orderStatus)
                            .set(OrderGoodsEntity::getOrderGoodsFinishTime, orderFinishedTime)) > CommonStatusEnum.FAIL.getCode();

                    boolean isSuccessByBaseForUpdate = this.baseMapper.update(null, new LambdaUpdateWrapper<OrderBaseEntity>()
                            .eq(OrderBaseEntity::getOrderId, orderId)
                            .set(OrderBaseEntity::getOrderStatus, orderStatus)
                            .set(OrderBaseEntity::getOrderFinishedTime, orderFinishedTime)) > CommonStatusEnum.FAIL.getCode();

                    if (isSuccessByGoodsForUpdate && isSuccessByBaseForUpdate) {
                        //计算售后最后时间
                        Calendar instance = Calendar.getInstance();
                        instance.setTime(orderFinishedTime);
                        instance.add(Calendar.DATE, 14);
                        Date orderLastReturnTime = instance.getTime();

                        //更新订单最后售后时间
                        this.baseMapper.updateByOrderBaseorderLastReturnTime(orderId, orderLastReturnTime);
                        //收货成功
                        result.setCode(CommonStatusEnum.SUCCESS.getCode());
                        result.setMessage(BizCodeEnume.GOODS_RECEIVED_SUCCESSFULLY.getMsg());
                        // 分佣订单售后时间更新
                        baseServiceClient.updateOrderAfterSale(orderId);
                        // 收货成功改变订单状态
                        payMentServiceClient.changeConsumeRecord(orderId);
                        // 收货成功，将金额存向卖家冻结金额
                        payMentServiceClient.addMoney(moneyMap);
                    } else {
                        result.setCode(CommonStatusEnum.FAIL.getCode());
                        result.setMessage(BizCodeEnume.GOODS_RECEIVED_FAILED.getMsg());
                    }
                }
                if (result.getCode() != CommonStatusEnum.FAIL.getCode() && (null == orderBaseEntity.getIntegralGoods() || 1 == orderBaseEntity.getIntegralGoods())) {
                    //查询积分规则
                    ResponseResult resultResp = baseServiceClient.queryIntegralRules();
                    Map<String, Integer> integralRules = (Map<String, Integer>) resultResp.getData();
                    //修改会员积分和会员等级
                    MemberMessageListIntegralDTO updateMemberMessageListIntegral = new MemberMessageListIntegralDTO();
                    //积比例
                    Integer ruleConsume = integralRules.get("ruleConsume");
                    if(ui.getPlusMember()!=null&&ui.getPlusMember()==1){
                        //查询用户是否开通plus会员 并且是否有折扣权益
                        ResponseResult selectplusmember = selectplusmemberjifen(userId);
                        String s = String.valueOf(selectplusmember.getData());
                        if (s != null && s != "" && s != "null"){
                            ruleConsume = Integer.valueOf(s);//倍率
                        }
                    }
                    BigDecimal jifen = money.multiply(new BigDecimal(ruleConsume));
                    long l = jifen.setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
                    ArrayList<String> list = new ArrayList<>();
                    list.add(userId);
                    updateMemberMessageListIntegral.setUserIdList(list);
                    updateMemberMessageListIntegral.setIntegral((int) l);
                    //1是增加积分 0 是扣除积分
                    updateMemberMessageListIntegral.setType(CommonType.commonStatus.YES.getCode());
                    userServiceClient.updateMemberIntegral(updateMemberMessageListIntegral);
                    //添加积分修改记录
                    Map<String, Object> pointParam = new HashMap<>();
                    pointParam.put("PointsLogType", CommonType.pointsLogType.GAIN.getCode());
                    pointParam.put("ClassId", CommonType.pointType.PURCHASE.getCode());
                    pointParam.put("PointsLogTime", DateUtils.getTime());
                    pointParam.put("PointsLogDesc", CommonType.pointType.PURCHASE.getDesc());
                    pointParam.put("PointsLogFlag", "reg");
                    pointParam.put("UserId", userId);
                    pointParam.put("orderId", orderId);
                    pointParam.put("PointsLogPoints", (int) l);
                    pointParam.put("PointsLogOperate", CommonType.pointType.PURCHASE.getDesc());
                    pointParam.put("proportion", ruleConsume);
                    userServiceClient.insertPointLogByMap(pointParam);
                    //商家购买供应商的商品 不直接进入商城  如果商家要上架改商品  需要重新走商品发布
                    OrderPayInfoVO orderPayInfo  = this.baseMapper.queryOrderInfo(orderId);
                    if(orderPayInfo.getOrderType().intValue() == CommonType.orderType.SUPPLY_TYPE.getCode()){
                        // 插入商品
                        Runnable orderThread = new SupplyOrderThread(goodServiceClient,orderBaseMapper,orderPayInfo.getPaymentNumber(),token);
                        Thread thread = new Thread(orderThread);
                        thread.start();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                GlobalTransactionContext.reload(RootContext.getXID()).rollback();
                return ResponseResult.fail(e.getMessage());
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        return result;
    }

    //查询积分
    public ResponseResult selectplusmemberjifen(String userId) {
        ResponseResult resultResp = new ResponseResult();
        PlusMemberEntityVO map1 = this.baseMapper.selectplusmember(userId);
        if (map1 != null){

            String string = null;

            String selectplusthali = map1.getPlusEquity();
            if (selectplusthali == null || selectplusthali == "" ){
                return  resultResp.fail(2, "权益为空", null);
            }
            String[] split = selectplusthali.split(",");
            List<Integer> appIdList = Stream.of(split).map(Integer::parseInt).collect(Collectors.toList());
            List<PlusEquityDTO> entities = JSON.parseArray(JSONObject.toJSONString(userServiceClient.selectplusequitys(appIdList).getData()), PlusEquityDTO.class);
            if (entities == null || !(entities.size() > 0)){
                return resultResp.fail(2, "权益错误", null);
            }
            for (PlusEquityDTO selectplusequity : entities) {
                if (selectplusequity.getEquityType() == 5){
                    String equityValue = selectplusequity.getEquityValue();
                    String[] strings = equityValue.split(":");
                    string = strings[1];
                }
            }
            return resultResp.success(1,"", string);
        }
        resultResp.setCode(5);
        return resultResp;
    }

    @Override
    public ResponseResult delayToReceiveGoods(Map<Object, Object> map) {
        ResponseResult result = new ResponseResult();
        String token = (String) map.get("token");
        boolean isExist = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (isExist) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                UserInfoDTO ui = new UserInfoDTO();
                // 获取user信息
                String userinfo = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + token);
                // String转object
                ui = mapper.readValue(userinfo, UserInfoDTO.class);
                String userId = ui.getUser().getUserId();
                String orderId = (String) map.get("orderId");
                //订单信息
                OrderBaseEntity orderBaseEntity = this.baseMapper.selectOne(new LambdaQueryWrapper<OrderBaseEntity>()
                        .eq(OrderBaseEntity::getBuyerUserId, userId).eq(OrderBaseEntity::getOrderId, orderId));
                Integer isAlreadyDelay = orderBaseEntity.getOrderDelayStatus();

                Date time = orderBaseEntity.getOrderReceiverDate();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String delayTime = sdf.format(time);
                if (isAlreadyDelay == 1) {

                    result.setMessage("该订单已延长至" + delayTime + "，请勿重复操作！");
                } else {
                    boolean isUpdateToDelayToReceiveGoods = this.baseMapper.updateDelayTime(userId, orderId);
                    if (isUpdateToDelayToReceiveGoods) {
                        result.setCode(CommonStatusEnum.SUCCESS.getCode());
                        result.setMessage("已成功为您延迟7天收货，请注意自动收货时间！");
                    } else {
                        result.setCode(CommonStatusEnum.FAIL.getCode());
                        result.setMessage("订单延长出错！");
                    }
                }
                return result;
            } catch (Exception e) {
                result.setCode(500);
                log.info("DelayToReceiveGoodsErrorResults:" + e.getMessage());
                return ResponseResult.fail(e.getMessage());
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
    }

    @Override
    public ResponseResult enquireSoldOrders(Map<String, Object> map) {
        String token = (String) map.get("token");
        boolean isExist = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (isExist) {
            try {
                UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
                String userId = map.get("userId") == null ? ui.getUserId() : (String) map.get("userId");
                String orderId = (String) map.get("orderId");
                // 查询订单信息
                SoldOrderByCommonalityDetailsVO sobcd = this.baseMapper.soldOrderByCommonalityDetails(userId, orderId);
                if(null != sobcd.getGiveawayInfo() && !sobcd.getGiveawayInfo().isEmpty()){
                    List<FullReductionGiftsVO> list = JsonUtils.string2Obj(sobcd.getGiveawayInfo(),List.class, FullReductionGiftsVO.class);
                    sobcd.setZengpinInfo(list);
                }
                //查询当前订单是否改价 如果 改价必须全单退
                Integer orderNum = orderGoodsMapper.queryOrderUpdatePrice(map);
                if(orderNum == 0 ){
                    sobcd.setUpdatePrice(false);
                }else{
                    if(!com.yuanfeng.commoms.util.StringUtils.isPositiveNumber(sobcd.getOrderAdjustFee())){
                        sobcd.setOrderAdjustFee(String.valueOf(Double.parseDouble(sobcd.getOrderAdjustFee()) * -1));
                    }
                    sobcd.setUpdatePrice(true);
                }

                if(ui != null){
                    sobcd.setUserInfo(ui);
                }
                //判断是否是门店自提订单，是则远程调用查询门店信息
                if(sobcd.getOrderIsShopTake() !=null && sobcd.getOrderIsShopTake() == 1){
                    if(sobcd.getOrderGateShopId() != null){
                        //远程调用查询门店信息
                        Map<String, Object> param = new HashMap<>();
                        param.put("shopGateId", sobcd.getOrderGateShopId());
                        ResponseResult resultResp = businessServiceClient.queryGateDetail(param);
                        GateDetailDTO gateDetailDTO = JSONObject.parseObject(JSONObject.toJSONString(resultResp.getData()), GateDetailDTO.class);
                        if (gateDetailDTO != null) {
                            sobcd.setGateDetailDTO(gateDetailDTO);
                        }
                    }
                }
                BigDecimal vPrice = new BigDecimal(0);
                // 优惠券总金额
                BigDecimal voucherTotalPrice = new BigDecimal(0);
                // 单一店铺优惠券金额
                BigDecimal voucherPrice = sobcd.getVoucherPrice();
                if (voucherPrice == null) {
                    vPrice = new BigDecimal(0);
                    voucherTotalPrice = voucherTotalPrice.add(vPrice);
                } else {
                    voucherTotalPrice = voucherTotalPrice.add(voucherPrice);
                }

                if (null != sobcd.getOrderBuyId()) {
                    ResponseResult orderPintuanMarkEntity = activityServiceClient.querySurplusNum(sobcd.getOrderBuyId());
                    if (!ObjectUtils.isEmpty(orderPintuanMarkEntity.getData())) {
                        Integer numberesultemaining = Integer.valueOf(orderPintuanMarkEntity.getData().toString());
                        sobcd.setNumberRemaining(numberesultemaining);
                    }
                }
                // 配送公司id
                Integer orderShippingExpressId = sobcd.getOrderShippingExpressId();
                // 获取快递信息
                ResponseResult expressResult = baseServiceClient.queryKdniaoExpresssInfo(orderShippingExpressId);
                if (expressResult.getData() != null) {
                    Map<String, Object> orderShippingExpressName = (Map<String, Object>) expressResult.getData();
                    sobcd.setOrderShippingExpressName(orderShippingExpressName.get("expressName").toString());
                }
                // 红包拆分价格
                BigDecimal orderesultptPrice = sobcd.getOrderRptPrice();
                // 红包
                sobcd.setRedpacketPrice(orderesultptPrice);
                sobcd.setRedpacketPrice(orderesultptPrice);
                Integer orderesultefundStatus = sobcd.getOrderRefundStatus();
                Integer orderesulteturnStatus = sobcd.getOrderReturnStatus();
                // 订单状态
                Integer normalStatus = sobcd.getOrderStatus();
                //虚拟订单 0 是 1 否
                Integer virtualGoods = sobcd.getVirtualGoods();
                // 1.线上支付  2.线下支付 3.货到付款
                Integer paymentCode = sobcd.getPaymentCode();
                if(null != paymentCode && 2 == paymentCode){
                    //查询线下支付的审核状态
                    OrderPaymentVocherEntity PaymentVocherPo = orderPaymentVocherMapper.selectOne(new LambdaQueryWrapper<OrderPaymentVocherEntity>()
                                                         .eq(OrderPaymentVocherEntity::getOrderId,orderId));
                    if(null != PaymentVocherPo){
                        sobcd.setReviewStatus(PaymentVocherPo.getReviewStatus());
                    }
                }
                Integer status = null;// 涉及退款退货订单状态
                if (normalStatus.equals(CommonType.orderStatus.TO_BE_SHIPPED.getCode())|| (null != virtualGoods && 0 == virtualGoods && CommonType.orderStatus.SHIPPED.getCode().equals(normalStatus))) {
                    // 未发货状态
                    if (orderesultefundStatus.equals(CommonType.orderRefundStatus.REFUNDING.getCode()) || orderesultefundStatus.equals(CommonType.orderRefundStatus.REFUND_FAILED.getCode())) {
                        // 未发货退款中
                        status = 22;
                    } else if (orderesultefundStatus.equals(CommonType.orderRefundStatus.REFUND_COMPLETED.getCode())) {
                        // 商家拒绝或审核通过，继续发货，但不可再次申请退款
                        status = 26;
                    } else if (orderesultefundStatus.equals(CommonType.orderRefundStatus.NO_REFUND.getCode()) && null != virtualGoods && 0 == virtualGoods) {
                        status = normalStatus;
                    }else {
                        status = 3;
                    }
                }else if (normalStatus.equals(CommonType.orderStatus.CONFIRM_RECEIPT.getCode())) {
                    // 已完成状态
                    if (orderesultefundStatus.equals(CommonType.orderRefundStatus.REFUNDING.getCode()) || orderesultefundStatus.equals(CommonType.orderRefundStatus.REFUND_FAILED.getCode())) {
                        // 收货退款中
                        status = 23;
                    } else if (orderesultefundStatus.equals(CommonType.orderRefundStatus.REFUND_COMPLETED.getCode())) {
                        status = 25;
                    } else if (orderesultefundStatus.equals(CommonType.orderRefundStatus.NO_REFUND.getCode()) && orderesulteturnStatus.equals(CommonType.orderReturnStatus.NO_RETURNS.getCode())) {
                        status = 6;
                    } else if (orderesulteturnStatus.equals(CommonType.orderReturnStatus.RETURNING_GOODS.getCode())) {
                        // 收货退货中
                        status = 24;
                    } else if (orderesulteturnStatus.equals(CommonType.orderReturnStatus.RETURN_COMPLETED.getCode())) {
                        status = 25;
                    }else{
                        status = 6;
                    }
                    if (null != sobcd.getOrderLastReturnTime() && DateUtils.compareDate(sobcd.getOrderLastReturnTime(), DateUtils.getNowDateToString())
                            &&  1 == virtualGoods) {
                        // 订单超过完成时间不可售后
                        status = 27;
                    }
                }else {
                    status = normalStatus;
                }
                // 存放最新状态
                sobcd.setOrderStatus(status);

                // 查询商品信息
                List<SoldOrderByGoodsDetailsVO> soldOrderByGoodsDetailsList = new ArrayList<>();
                List<SoldOrderByGoodsDetailsVO> sobgdList = this.baseMapper.soldOrderByGoodsDetails(userId, orderId);
                Long actOverplusTime = null;
                for (SoldOrderByGoodsDetailsVO soldOrderByGoodsDetails : sobgdList) {
                    // 退货状态
                    Integer goodsRefundStatus = soldOrderByGoodsDetails.getGoodsRefundStatus();
                    // 退款状态
                    Integer goodsReturnStatus = soldOrderByGoodsDetails.getGoodsReturnStatus();
                    if (goodsRefundStatus.equals(CommonType.orderRefundStatus.NO_REFUND.getCode())) {
                        // 不涉及退货(申请售后)
                        soldOrderByGoodsDetails.setGoodsStatus(0);
                    } else if (goodsRefundStatus.equals(CommonType.orderRefundStatus.REFUNDING.getCode())) {
                        // 仅退货(退货进行中)
                        soldOrderByGoodsDetails.setGoodsStatus(1);
                    } else if (goodsRefundStatus.equals(CommonType.orderRefundStatus.REFUND_COMPLETED.getCode())) {
                        // 仅退货(退货完成)
                        soldOrderByGoodsDetails.setGoodsStatus(2);
                    } else if (goodsReturnStatus.equals(CommonType.orderReturnStatus.NO_RETURNS.getCode())) {
                        // 不涉及退款(申请售后)
                        soldOrderByGoodsDetails.setGoodsStatus(0);
                    } else if (goodsReturnStatus.equals(CommonType.orderReturnStatus.RETURNING_GOODS.getCode())) {
                        // 仅退款(退款进行中)
                        soldOrderByGoodsDetails.setGoodsStatus(3);
                    } else if (goodsReturnStatus.equals(CommonType.orderReturnStatus.RETURN_COMPLETED.getCode())) {
                        // 仅退款(退款完成)
                        soldOrderByGoodsDetails.setGoodsStatus(4);
                    }
                    soldOrderByGoodsDetailsList.add(soldOrderByGoodsDetails);
                    sobcd.setSoldOrderByGoodsDetailsList(soldOrderByGoodsDetailsList);
                    //若为未付款秒杀订单，显示剩余支付时间
                    if(1 == status){
                        Date seckillCancelTime = soldOrderByGoodsDetails.getSeckillCancelTime();
                        if(null != seckillCancelTime){
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            try {
                                if(new Date().before(seckillCancelTime)){
                                    //Long overplusTime = DateUtils.getSecondByMinusDate(new Date(),seckillCancelTime);
                                    Long overplusTime = seckillCancelTime.getTime();
                                    if(sobcd.getSeckillExpireTime() == null){
                                        sobcd.setSeckillExpireTime(overplusTime);
                                    }else if(sobcd.getSeckillExpireTime()>overplusTime){
                                        sobcd.setSeckillExpireTime(overplusTime);
                                    }

                                }
                            }catch (Exception e){
                                log.error(e.getMessage());
                            }
                        }
                    }
                }
                Date orderReceiverDate = this.baseMapper.selectById(orderId).getOrderReceiverDate();
                if (orderReceiverDate != null){
                    sobcd.setOrderReceiverDate(DateUtils.addDays(orderReceiverDate,7));
                }

                OrderReturnEntity entity = orderReturnMapper.selectOne(new LambdaQueryWrapper<OrderReturnEntity>()
                        .eq(OrderReturnEntity::getOrderId, orderId));
                if (entity != null) {
                    sobcd.setReturnShippingCode(entity.getReturnShippingCode());
                    sobcd.setReturnPostId(entity.getReturnPostCode());
                }
                ResponseResult res = baseServiceClient.queryExpressList(map);
                if (null != res.getData()) {
                    List<LinkedHashMap<Object, Object>> list = (List<LinkedHashMap<Object, Object>>) res.getData();
                    for (LinkedHashMap<Object, Object> expresult : list) {
                        if (null != expresult.get("expressId") && null != sobcd.getReturnPostId()) {
                            if (expresult.get("expressId").toString().equals(sobcd.getReturnPostId().toString())) {
                                sobcd.setReturnPostName((String) expresult.get("expressName"));
                            }
                        }
                    }
                }
                // 判断集合是否为空
                if (sobcd == null) {
                    // 为空输出信息
                   return ResponseResult.fail(BizCodeEnume.SELECT_DATA_NULL);
                } else {
                    return ResponseResult.success(sobcd);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.info("EnquireSoldOrdersErrorResults:" + e.getMessage());
                return ResponseResult.fail(e.getMessage());
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult addComments(CommentsListDTO cl) throws TransactionException {
        try {
            ResponseResult result = new ResponseResult();
            String token = cl.getToken();
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
            if (userInfo != null) {
                String userId = userInfo.getUserId();
                String userName = userInfo.getUserName();
                String userAvatar = userInfo.getUserAvatar();
                String orderId = cl.getOrderId();
                Integer shopId = cl.getShopId();
                String resultType = null;
                Date createTime = DateUtils.getNowDate();
                // 评论显示状态
                Integer status = 1;
                String goodsName = null;
                String goodsSpec = null;
                Integer evaluationFrom = cl.getEvaluationFrom();
                // 描述相符评分
                Integer evaluationDesccredit = cl.getEvaluationDesccredit();
                // 服务态度评分
                Integer evaluationServicecredit = cl.getEvaluationServicecredit();
                // 发货速度评分
                Integer evaluationDeliverycredit = cl.getEvaluationDeliverycredit();
                // 查找店铺名
                OrderBaseEntity orderBaseEntity = this.baseMapper.selectOne(new LambdaQueryWrapper<OrderBaseEntity>()
                        .eq(OrderBaseEntity::getBuyerUserId, userId).eq(OrderBaseEntity::getOrderId, orderId));
                String shopName = null;
                if (null != orderBaseEntity) {
                    shopName = orderBaseEntity.getShopName();
                }

                if (cl.getGoodsList().isEmpty()) {
                    // 店铺评分
                    Map<String, Object> param = new HashMap<>();
                    param.put("shopId", shopId);
                    param.put("shopName", shopName);
                    param.put("userId", userId);
                    param.put("userName", userName);
                    param.put("orderId", orderId);
                    param.put("evaluationDesccredit", evaluationDesccredit);
                    param.put("evaluationServicecredit", evaluationServicecredit);
                    param.put("evaluationDeliverycredit", evaluationDeliverycredit);
                    param.put("evaluationCreateTime", createTime);

                    result = businessServiceClient.saveShopEvaluationInfo(param);
                    return result;
                } else {
                    for (int i = 0; i < cl.getGoodsList().size(); i++) {
                        Integer commonId = cl.getGoodsList().get(i).getCommonId();
                        Integer goodsId = cl.getGoodsList().get(i).getGoodsId();
                        // 是否匿名
                        Integer isAnonymous = cl.getIsanonymous();
                        String feedBack = cl.getGoodsList().get(i).getFeedback();
                        if (null != feedBack) {
                            //敏感词过滤
                            feedBack = SensitiveWord.filterInfo(feedBack);
                        }
                        Integer score = cl.getGoodsList().get(i).getScores();
                        switch (score) {
                            case 5:
                                resultType = "good";
                                break;
                            case 4:
                                resultType = "good";
                                break;
                            case 3:
                                resultType = "neutral";
                                break;
                            case 2:
                                resultType = "bad";
                                break;
                            case 1:
                                resultType = "bad";
                                break;
                        }
                        List<String> imagesList = cl.getGoodsList().get(i).getImageList();
                        String images = org.apache.commons.lang.StringUtils.join(imagesList, ",");
                        List<OrderGoodsEntity> goodsDetails = orderGoodsMapper.selectList(new LambdaQueryWrapper<OrderGoodsEntity>()
                                .eq(OrderGoodsEntity::getOrderId, orderId)
                                .eq(OrderGoodsEntity::getGoodsId, goodsId));

                        goodsName = goodsDetails.get(0).getGoodsName();
                        goodsSpec = goodsDetails.get(0).getOrderSpecChineseValue();

                        Map<String, Object> mapGoods = new HashMap<>();
                        mapGoods.put("userId", userId);
                        mapGoods.put("userName", userName);
                        mapGoods.put("userAvatar", userAvatar);
                        mapGoods.put("orderId", orderId);
                        mapGoods.put("shopId", shopId);
                        mapGoods.put("shopName", shopName);
                        mapGoods.put("commonId", commonId);
                        mapGoods.put("goodsId", goodsId);
                        mapGoods.put("goodsName", goodsName);
                        mapGoods.put("goodsSpec", goodsSpec);
                        mapGoods.put("score", score);
                        mapGoods.put("result", resultType);
                        mapGoods.put("feedBack", feedBack);
                        mapGoods.put("isAnonymous", isAnonymous);
                        mapGoods.put("createTime", createTime);
                        mapGoods.put("status", status);
                        mapGoods.put("images", images);
                        mapGoods.put("evaluationFrom", evaluationFrom);
                        boolean isInsertByGoods = orderGoodsEvaluationMapper.commentsInsertByGoods(mapGoods);
                        Map<String, Object> map = new HashMap<>();
                        map.put("commonId", commonId);
                        goodServiceClient.updateCommentCount(map);
                        List<Integer> list = new ArrayList<>();
                        list.add(commonId);
                        map.put("commonIdS", list);
                        // 1 是添加  2是删除
                        map.put("type", 1);
                        ExecutorService executorService = Executors.newSingleThreadExecutor();
                        executorService.submit(() -> {
                            //发送消息到MQ
                            MqSendUtils.mqSendGoods(map);
                        });
                        // 关闭线程池
                        executorService.shutdown();

                        // 商品评价
                        if (isInsertByGoods) {
                            result.setMessage(CommonStatusEnum.SUCCESS.getValue());
                            // 评价成功，改变状态
                            this.baseMapper.update(null, new LambdaUpdateWrapper<OrderBaseEntity>()
                                    .eq(OrderBaseEntity::getBuyerUserId, userId)
                                    .eq(OrderBaseEntity::getOrderId, orderId)
                                    .set(OrderBaseEntity::getOrderBuyerEvaluationStatus, 1));

                            orderGoodsMapper.update(null, new LambdaUpdateWrapper<OrderGoodsEntity>()
                                    .eq(OrderGoodsEntity::getBuyerUserId, userId)
                                    .eq(OrderGoodsEntity::getOrderId, orderId)
                                    .set(OrderGoodsEntity::getOrderGoodsEvaluationStatus, 1));

                        } else {
                            result.setMessage(CommonStatusEnum.FAIL.getValue());
                        }
                    }
                    // 店铺评分
                    Map<String, Object> param = new HashMap<>();
                    param.put("shopId", shopId);
                    param.put("shopName", shopName);
                    param.put("userId", userId);
                    param.put("userName", userName);
                    param.put("orderId", orderId);
                    param.put("evaluationDesccredit", evaluationDesccredit);
                    param.put("evaluationServicecredit", evaluationServicecredit);
                    param.put("evaluationDeliverycredit", evaluationDeliverycredit);
                    param.put("evaluationCreateTime", createTime);

                    result = businessServiceClient.saveShopEvaluationInfo(param);
                }
            } else {
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            // 回滚
            GlobalTransactionContext.reload(RootContext.getXID()).rollback();
            return ResponseResult.fail(e.getMessage());
        }
    }

    @Override
    public ResponseResult ordersTotal(Map<Object, Object> map) {
        ResponseResult rr = new ResponseResult();
        BusinessManageOrderTotalVO omot = new BusinessManageOrderTotalVO();
        String token = (String) map.get("token");
        boolean isExist = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (isExist) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                UserInfoVO ui = new UserInfoVO();
                // 获取user信息
                String userinfo = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + token);
                ui = ParseTokenUtils.getUserInfoByToken(token);
                Integer shopId = Integer.valueOf(ui.getShopId());
                if (null == shopId) {
                    rr.setCode(CommonStatusEnum.FAIL.getCode());
                    rr.setMessage(BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
                    return rr;
                }
                Integer orderSource = 2;
                if (null != ui.getShopType() && 2 == ui.getShopType()) {
                    //查询待发货订单
                    orderSource = 1;
                }
                // 待付款
                int WaitingForPayment = this.baseMapper.WaitingForPaymentTotal(shopId, orderSource);
                // 待发货
                int WaitForTheDelivery = this.baseMapper.WaitForTheDeliveryTotal(shopId, orderSource);
                // 已发货
                int Shipped = this.baseMapper.shippedTotal(shopId, orderSource);
                // 已完成
                int OffTheStocks = this.baseMapper.OffTheStocksTotal(shopId, orderSource);
                // 退货订单
                int SalesReturn = this.baseMapper.SalesReturnTotal(shopId, orderSource);
                // 退款订单
                int Refund = this.baseMapper.RefundTotal2(shopId, orderSource);
                omot.setWaitingForPayment(WaitingForPayment);
                omot.setWaitForTheDelivery(WaitForTheDelivery);
                omot.setShipped(Shipped);
                omot.setOffTheStocks(OffTheStocks);
                omot.setSalesReturn(SalesReturn);
                omot.setRefund(Refund);
                rr.setCode(1);
                rr.setData(omot);
            } catch (Exception e) {
                rr.setCode(500);
                log.info("OrdersTotalErrorResults:" + e.getMessage());
            }
        } else {
            rr.setCode(CommonStatusEnum.FAIL.getCode());
            rr.setMessage(BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        return rr;
    }

    @Override
    public ResponseResult salesNo(Map<Object, Object> map) {
        ResponseResult rr = new ResponseResult();
        String token = (String) map.get("token");
        boolean isExist = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (isExist) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                UserInfoVO ui = new UserInfoVO();
                // 获取user信息
                String userinfo = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + token);
                ui = ParseTokenUtils.getUserInfoByToken(token);
                Integer shopId = Integer.valueOf(ui.getShopId());
                if (null == shopId) {
                    rr.setCode(CommonStatusEnum.FAIL.getCode());
                    rr.setMessage(BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
                    return rr;
                }
                List<SalesRankingVO> sr = this.baseMapper.querySalesRanking(shopId);
                if (sr != null) {
                    rr.setCode(CommonStatusEnum.SUCCESS.getCode());
                    rr.setData(sr);
                    rr.setMessage(BizCodeEnume.OPERATION_SUCCESSFUL.getMsg());
                } else {
                    rr.setCode(CommonStatusEnum.FAIL.getCode());
                    rr.setMessage(BizCodeEnume.OPERATION_FAILED.getMsg());
                }
            } catch (Exception e) {
                rr.setCode(500);
                log.info("SalesNoErrorResults:" + e.getMessage());
            }
        } else {
            rr.setCode(CommonStatusEnum.FAIL.getCode());
            rr.setMessage(BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        return rr;
    }

    @Override
    public ResponseResult calculatedSales(Map<Object, Object> map) {
        ResponseResult rr = new ResponseResult();
        String token = (String) map.get("token");
        Integer shopType = (Integer) map.get("shopType");
        boolean isExist = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (isExist) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                UserInfoVO ui = new UserInfoVO();
                // 获取user信息
                String userinfo = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + token);
                ui = ParseTokenUtils.getUserInfoByToken(token);
                Integer shopId = Integer.valueOf(ui.getShopId());
                if (null == shopId) {
                    rr.setCode(CommonStatusEnum.FAIL.getCode());
                    rr.setMessage(BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
                    return rr;
                }
                //销售额列表-今日,本周,本月
                List<SaleRoomVO> srList = this.baseMapper.querySaleByShopId(shopId, shopType);
                return ResponseResult.success(srList);
            } catch (Exception e) {
                rr.setCode(500);
                log.info("CalculatedSalesErrorResults:" + e.getMessage());
            }
        } else {
            rr.setCode(CommonStatusEnum.FAIL.getCode());
            rr.setMessage(BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        return rr;
    }

    @Override
    public ResponseResult queryVirtualOrderByEvaluation(Map<String, Object> map) {
        String token = (String) map.get("token");
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
        String userId = ui.getUserId();
        // 待评价
        Integer waitingEvaluation = 0;
        // 已完成
        Integer offTheStocks = 6;
        IPage<OrderListVO> orderList;
        Map<String, Object> mapOrder = new HashMap<>();

        mapOrder.put("waitingEvaluation", waitingEvaluation);
        mapOrder.put("offTheStocks", offTheStocks);
        if (null == map.get("virtualGoods") || (Integer) map.get("virtualGoods") == 0) {
            mapOrder.put("userId", userId);
            //查询待评价虚拟订单商品信息
            orderList = this.baseMapper.queryWaitingEvaluationVirtualOrder(new Query<OrderListVO>().getPage(map), mapOrder);
        } else {
            String buyUserId = map.get("buyUserId") == null ? "0" : map.get("buyUserId").toString();
            List<String> userIdList = getEmployees(ui, userId, buyUserId);
            mapOrder.put("userIdList", userIdList);
            //查询待评价非虚拟订单商品信息
            orderList = this.baseMapper.queryWaitingEvaluationOrder(new Query<OrderListVO>().getPage(map), mapOrder);
        }
        BigDecimal paymentPrice = new BigDecimal(0);
        for (int i = 0; i < orderList.getRecords().size(); i++) {
            Integer goodsNum = 0;
            String orderId = orderList.getRecords().get(i).getOrderId();
            // 查询待评价商品信息
            List<GoodsDetailsListVO> goodsDetailsList = this.baseMapper.queryGoodsList(orderId);
            orderList.getRecords().get(i).setGoodsDetailsList(goodsDetailsList);
            // 退款状态
            Integer orderRefundStatus = orderList.getRecords().get(i).getOrderRefundStatus();
            // 退货状态
            Integer orderReturnStatus = orderList.getRecords().get(i).getOrderReturnStatus();
            // 订单状态
            Integer normalStatus = orderList.getRecords().get(i).getOrderStatus();
            // 虚拟订单
            Integer virtualGoods = orderList.getRecords().get(i).getVirtualGoods();
            // 涉及退款退货订单状态
            Integer status = null;
            if (normalStatus.equals(CommonType.orderStatus.TO_BE_SHIPPED.getCode()) ||
                    (virtualGoods != null && 0 == virtualGoods&& 4 == normalStatus)) {
                // 未发货状态
                if (orderRefundStatus.equals(CommonType.orderRefundStatus.REFUNDING.getCode())) {
                    // 未发货退款中
                    status = 22;
                } else if (orderRefundStatus.equals(CommonType.orderRefundStatus.REFUND_COMPLETED.getCode())) {
                    // 商家拒绝或审核通过，继续发货，但不可再次申请退款
                    status = 26;
                } else if (orderRefundStatus.equals(CommonType.orderRefundStatus.NO_REFUND.getCode())) {
                    status = 3;
                }
            } else if (normalStatus.equals(CommonType.orderStatus.CONFIRM_RECEIPT.getCode())) {
                // 已完成状态
                if (orderRefundStatus.equals(CommonType.orderRefundStatus.REFUNDING.getCode())) {
                    // 收货退款中
                    status = 23;
                } else if (orderRefundStatus.equals(CommonType.orderRefundStatus.REFUND_COMPLETED.getCode())) {
                    status = 25;
                } else if (orderRefundStatus.equals(CommonType.orderRefundStatus.NO_REFUND.getCode()) && orderReturnStatus.equals(CommonType.orderReturnStatus.NO_RETURNS.getCode())) {
                    status = 6;
                } else if (orderReturnStatus.equals(CommonType.orderReturnStatus.RETURNING_GOODS.getCode())) {
                    // 收货退货中
                    status = 24;
                } else if (orderReturnStatus.equals(CommonType.orderReturnStatus.RETURN_COMPLETED.getCode())) {
                    status = 25;
                }
            } else {
                status = normalStatus;
            }
            // 存放最新状态
            orderList.getRecords().get(i).setOrderStatus(status);
            for (int j = 0; j < goodsDetailsList.size(); j++) {
                // 计算共有几件商品
                Integer goodsnum = goodsDetailsList.get(j).getOrderGoodsNum();
                goodsNum += goodsnum;
                orderList.getRecords().get(i).setGoodsNum(goodsNum);

                // 计算商品总价
                // 单个商品价格
                BigDecimal orderGoodsAmount = goodsDetailsList.get(j).getOrderGoodsAmount();
                paymentPrice = paymentPrice.add(orderGoodsAmount).setScale(2, BigDecimal.ROUND_UP);
            }
            // 退款实际价格
            orderList.getRecords().get(i).setRefundRealPrice(orderList.getRecords().get(i).getOrderGoodsAmount());
            // 总付款价格
            orderList.getRecords().get(i).setShopTotalPrice(orderList.getRecords().get(i).getOrderPaymentAmount());
            orderList.getRecords().get(i).setOrderTotalPrice(orderList.getRecords().get(i).getOrderPaymentAmount());
        }
        return ResponseResult.success(PageUtils.getPage(orderList));
    }

    @Override
    public ResponseResult queryIntegralOrders(Map<String, Object> map) {
        String token = (String) map.get("token");
        boolean isExist = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (isExist) {
            String userId = null;
            try {
                ObjectMapper mapper = new ObjectMapper();
                // 获取user信息
                String userinfo = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + token);
                // String转object
                UserInfoDTO dto = mapper.readValue(userinfo, UserInfoDTO.class);
                UserInfoVO ui = dto.getUser();
                // 发送人id
                userId = ui.getUserId();
                // 订单状态
                Integer orderStatus = Integer.valueOf(map.get("orderStatus").toString());
                Integer orderStatusNum = null;
                String allOrders = null;
                if (orderStatus == 1) {
                    // 全部订单
                    allOrders = "' '";
                } else if (orderStatus == 2) {
                    // 待付款
                    orderStatusNum = 1;
                } else if (orderStatus == 3) {
                    // 待发货
                    orderStatusNum = 3;
                } else if (orderStatus == 4) {
                    // 待收货
                    orderStatusNum = 4;
                } else if (orderStatus == 5) {
                    // 已完成
                    orderStatusNum = 6;
                }
                IPage<OrderBaseEntity> page = this.page(new Query<OrderBaseEntity>().getPage(map),
                        new LambdaQueryWrapper<OrderBaseEntity>().eq(OrderBaseEntity::getBuyerUserId, userId)
                                .eq(OrderBaseEntity::getIntegralGoods, 0)
                                .eq(OrderBaseEntity::getOrderDel, 0)
                                .eq(orderStatusNum != null && orderStatusNum == 3, OrderBaseEntity::getOrderStatus, orderStatusNum)
                                .ne(orderStatusNum != null && orderStatusNum == 3, OrderBaseEntity::getGroupbuyStatus, 1)
                                .eq(orderStatusNum != null && orderStatusNum != 3, OrderBaseEntity::getOrderStatus, orderStatusNum)
                                .orderByDesc(OrderBaseEntity::getOrderCreateTime));
                // 商品总价
                BigDecimal paymentPrice = new BigDecimal(0);
                for (int i = 0; i < page.getRecords().size(); i++) {
                    Integer goodsNum = 0;
                    String orderId = page.getRecords().get(i).getOrderId();
                    List<GoodsDetailsListVO> goodsDetailsList = orderGoodsMapper.queryGoodsList(orderId);
                    page.getRecords().get(i).setGoodsDetailsList(goodsDetailsList);
                    // 退款状态
                    String orderRefundStatus = page.getRecords().get(i).getOrderRefundStatus();
                    // 退货状态
                    String orderReturnStatus = page.getRecords().get(i).getOrderReturnStatus();
                    // 订单状态
                    Integer normalStatus = page.getRecords().get(i).getOrderStatus();
                    // 涉及退款退货订单状态
                    Integer status = null;
                    status = normalStatus;
                    // 存放最新状态
                    page.getRecords().get(i).setOrderStatus(status);
                    for (int j = 0; j < goodsDetailsList.size(); j++) {
                        // 计算共有几件商品
                        Integer goodsnum = goodsDetailsList.get(j).getOrderGoodsNum();
                        goodsNum += goodsnum;
                        page.getRecords().get(i).setGoodsNum(goodsNum);

                        // 计算商品总价
                        // 单个商品价格
                        BigDecimal orderGoodsAmount = goodsDetailsList.get(j).getOrderGoodsAmount();
                        paymentPrice = paymentPrice.add(orderGoodsAmount).setScale(2, BigDecimal.ROUND_UP);

                        //根据SPU获取商品状态   -- 商品状态 0下架，1正常，10违规（禁售）,2店铺下架商品下架,3商品删除
                        Integer commonId = goodsDetailsList.get(j).getCommonId();
                        Integer goodsid = goodsDetailsList.get(j).getGoodsId();
                        ResponseResult rr2 = goodServiceClient.getGoodsDetails(goodsid);
                        if (rr2.getCode() != 1) {
                            return ResponseResult.fail(BizCodeEnume.NO_INFORMATION_OBTAINED);
                        } else {
                            String goodsDetails = rr2.getData().toString();
                            // json转对象
                            ReceiveGoodsDetailsDTO receiveGoodsDetails = JsonUtils.string2Obj(goodsDetails,
                                    ReceiveGoodsDetailsDTO.class);
                            goodsDetailsList.get(j).setGoodsIntegral(receiveGoodsDetails.getNeedIntegral());
                        }
                        Integer commonState = this.baseMapper.selCommonStateBySPU(commonId);
                        goodsDetailsList.get(j).setCommonState(commonState);
                    }
                    System.out.println("-----groupBuyStatus----" + page.getRecords().get(i).getOrderBuyId());
                    if (page.getRecords().get(i).getOrderBuyId() != null) {

                        Map<String, Object> param = new HashMap<>();
                        param.put("id", page.getRecords().get(i).getOrderBuyId());
                        ResponseResult orderPintuanMarkEntity = activityServiceClient.selectPiecingTogetherMarkInfo(param);
                        if (!ObjectUtils.isEmpty(orderPintuanMarkEntity.getData())) {
                            Map<String, Object> ptMap = ParseMapUtils.beanToMap(orderPintuanMarkEntity.getData());
                            Integer numberesultemaining = Integer.valueOf(ptMap.get("surplusNum").toString());
                            page.getRecords().get(i).setNumberRemaining(numberesultemaining);
                        }
                    }
                    // 每家店铺总计价格
                    page.getRecords().get(i).setShopOrderTotalPrice(paymentPrice);
                    // 退款实际价格
                    page.getRecords().get(i).setRefundRealPrice(page.getRecords().get(i).getOrderGoodsAmount());
                    // 总付款价格
                    page.getRecords().get(i).setOrderTotalPrice(page.getRecords().get(i).getOrderPaymentAmount());
                }

                return ResponseResult.success(PageUtils.getPage(page));
            } catch (Exception e) {
                log.info("queryOrdersErrorResults:" + e.getMessage());
                return ResponseResult.fail(e.getMessage());
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
    }

    @Override
    public ResponseResult queryIntegralOrderByEvaluation(Map<String, Object> map) {
        String token = (String) map.get("token");

        boolean isExist = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (isExist) {
            String userId = RedisUtil.get(YFConfig.YF_USER_TOKEN_USERID + token);
            // 已完成
            Integer offTheStocks = 6;
            String timeEnd = (String) map.get("timeEnd");
            String timeStart = (String) map.get("timeStart");
            String orderNo = (String) map.get("orderNo");

            Map<String, Object> mapOrder = new HashMap<>();
            mapOrder.put("userId", userId);
            mapOrder.put("offTheStocks", offTheStocks);
            mapOrder.put("timeStart", timeStart);
            mapOrder.put("timeEnd", timeEnd);
            mapOrder.put("orderNo", orderNo);
            // 查询待评价订单商品信息
            IPage<OrderListVO> page = this.baseMapper.queryIntegralWaitingEvaluationOrder(new Query<OrderListVO>().getPage(map), mapOrder);
            BigDecimal paymentPrice = new BigDecimal(0);
            for (int i = 0; i < page.getRecords().size(); i++) {
                Integer goodsNum = 0;
                String orderId = page.getRecords().get(i).getOrderId();
                // 查询待评价商品信息
                List<GoodsDetailsListVO> goodsDetailsList = orderGoodsMapper.queryGoodsList(orderId);
                page.getRecords().get(i).setGoodsDetailsList(goodsDetailsList);
                // 退款状态
                Integer orderRefundStatus = page.getRecords().get(i).getOrderRefundStatus();
                // 退货状态
                Integer orderReturnStatus = page.getRecords().get(i).getOrderReturnStatus();
                // 订单状态
                Integer normalStatus = page.getRecords().get(i).getOrderStatus();
                // 涉及退款退货订单状态
                Integer status = null;
                if (normalStatus.equals(CommonType.orderStatus.TO_BE_SHIPPED.getCode())) {
                    // 未发货状态
                    if (orderRefundStatus.equals(CommonType.orderRefundStatus.REFUNDING.getCode())) {
                        // 未发货退款中
                        status = 22;
                    } else if (orderRefundStatus.equals(CommonType.orderRefundStatus.REFUND_COMPLETED.getCode())) {
                        // 商家拒绝或审核通过，继续发货，但不可再次申请退款
                        status = 26;
                    } else if (orderRefundStatus.equals(CommonType.orderRefundStatus.NO_REFUND.getCode())) {
                        status = 3;
                    }
                } else if (normalStatus.equals(CommonType.orderStatus.CONFIRM_RECEIPT.getCode())) {
                    // 已完成状态
                    if (orderRefundStatus.equals(CommonType.orderRefundStatus.REFUNDING.getCode())) {
                        // 收货退款中
                        status = 23;
                    } else if (orderRefundStatus.equals(CommonType.orderRefundStatus.REFUND_COMPLETED.getCode())) {
                        status = 25;
                    } else if (orderRefundStatus.equals(CommonType.orderRefundStatus.NO_REFUND.getCode()) && orderReturnStatus.equals(CommonType.orderReturnStatus.NO_RETURNS.getCode())) {
                        status = 6;
                    } else if (orderReturnStatus.equals(CommonType.orderReturnStatus.RETURNING_GOODS.getCode())) {
                        // 收货退货中
                        status = 24;
                    } else if (orderReturnStatus.equals(CommonType.orderReturnStatus.RETURN_COMPLETED.getCode())) {
                        status = 25;
                    }
                    if (null != page.getRecords().get(i).getOrderLastReturnTime() && DateUtils.compareDate(page.getRecords().get(i).getOrderLastReturnTime(), DateUtils.getNowDateToString())) {
                        // 订单超过完成时间不可售后
                        status = 27;
                    }
                } else {
                    status = normalStatus;
                }
                // 存放最新状态
                page.getRecords().get(i).setOrderStatus(status);
                for (int j = 0; j < goodsDetailsList.size(); j++) {
                    // 计算共有几件商品
                    Integer goodsnum = goodsDetailsList.get(j).getOrderGoodsNum();
                    goodsNum += goodsnum;
                    page.getRecords().get(i).setGoodsNum(goodsNum);

                    // 计算商品总价
                    // 单个商品价格
                    BigDecimal orderGoodsAmount = goodsDetailsList.get(j).getOrderGoodsAmount();
                    paymentPrice = paymentPrice.add(orderGoodsAmount).setScale(2, BigDecimal.ROUND_UP);
                }
                // 退款实际价格
                page.getRecords().get(i).setRefundRealPrice(page.getRecords().get(i).getOrderGoodsAmount());
                // 总付款价格
                page.getRecords().get(i).setOrderTotalPrice(page.getRecords().get(i).getOrderPaymentAmount());
            }
            return ResponseResult.success(PageUtils.getPage(page));
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
    }

    @Override
    public ResponseResult queryOrderInvoiceList(Map<String, Object> param) {
        String token = (String) param.get("token");
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
        if (ui == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
        } else {
            List<String> userIdList = new ArrayList<>();
            if (param.get("buyUserId") != null) {
                String buyUserId = (String) param.get("buyUserId");
                userIdList.add(buyUserId);
            } else {
                userIdList.add(ui.getUserId());
                Map<String, Object> detail = this.baseMapper.queryBusiness(ui.getUserId(), null);
                if (detail != null && ui.getIsEmployee() != null && ui.getIsEmployee() != 1 && ui.getIsBusiness() == 1) {
                    List<String> list = this.baseMapper.queryEmployeesList(detail.get("businessId").toString());
                    if (list.contains(ui.getUserId())) {
                        userIdList = list;
                    }
                }
            }
            param.put("userIdList", userIdList);
        }
        try {
            IPage<OrderBaseEntity> page = this.baseMapper.queryOrderGoodsInfo(new Query<OrderBaseEntity>().getPage(param),
                    param);
            for (OrderBaseEntity order : page.getRecords()) {
                param.put("orderId", order.getOrderId());
                List<OrderGoodsEntity> goodsInfo = orderGoodsMapper.selectList(new LambdaQueryWrapper<OrderGoodsEntity>()
                        .eq(OrderGoodsEntity::getOrderId, order.getOrderId()));
                order.setGoodsList(goodsInfo);
                param.put("invoiceId", order.getInvoiceId());
                OrderInvoiceInfoEntity invoice = orderInvoiceInfoMapper.selectById(order.getInvoiceId());
                if (invoice != null) {
                    order.setInvoiceType(invoice.getInvoiceType());
                }
                Map<String, Object> tmp = this.baseMapper.getInvoiceSwitchInfo(order.getShopId());
                if (null != tmp) {
                    order.setInvoiceAuditStatus((Integer) tmp.get("invoiceAuditStatus"));
                    Integer invoiceSwitchStatus = (Integer) tmp.get("invoiceSwitchStatus");
                    Integer invoiceAuditStatus = (Integer) tmp.get("invoiceAuditStatus");
                    if (1 == invoiceAuditStatus && 1 == invoiceSwitchStatus) {
                        order.setInvoiceSwitchStatus(1);
                    } else if (0 == invoiceAuditStatus && 0 == invoiceSwitchStatus) {
                        order.setInvoiceSwitchStatus(1);
                    } else if (2 == invoiceAuditStatus && 0 == invoiceSwitchStatus) {
                        order.setInvoiceSwitchStatus(1);
                    } else {
                        order.setInvoiceSwitchStatus(0);
                    }
                } else {
                    order.setInvoiceSwitchStatus(0);
                    order.setInvoiceAuditStatus(3);

                }
                Date orderFinishTime = order.getOrderFinishedTime();
                order.setIsOutDate(0);
                if (null != orderFinishTime) {
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(orderFinishTime);
                    cal.add(Calendar.DATE, 90);
                    Date countDate = cal.getTime();
                    if (countDate.compareTo(new Date()) < 0) {
                        order.setIsOutDate(1);
                    }
                }
            }
            return ResponseResult.success(PageUtils.getPage(page));
        } catch (Exception e) {
            return ResponseResult.fail(e.getMessage());
        }
    }

    @Override
    public ResponseResult orderSellingTransaction(SellingInputDTO sellingPara) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(sellingPara.getToken());
        if (userInfo == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }

        //分页
        //将对象转换为map
        Map data = null;
        try {
            data = ParseMapUtils.beanToMap(sellingPara);
        } catch (IllegalAccessException e) {
        }
        //分页查询数据
        IPage<SellingOrderVO> page = this.baseMapper.selectSellingOrderNew(new Query<SellingOrderVO>().getPage(data), sellingPara);
        BigDecimal orderMoney = this.baseMapper.querySellingOrderMoneynNew(sellingPara);
        List<SellingOrderVO> sellingList = page.getRecords();
        if (CollectionUtils.isNotEmpty(sellingList)) {
            Integer returnFlag = 0;
            for (SellingOrderVO sellingOrderPara : sellingList) {
                Integer virtualGoods = sellingOrderPara.getVirtualGoods();
                Integer orderIsShopTake = sellingOrderPara.getOrderIsShopTake();
                if( null != orderIsShopTake && 1 == orderIsShopTake){
                    sellingOrderPara.setOrderType(3);
                }else{
                    if(null != virtualGoods && 0 == virtualGoods){
                        sellingOrderPara.setOrderType(2);
                        sellingOrderPara.setPastDue(sellingOrderPara.getPastDue());
                        sellingOrderPara.setIsCancel(sellingOrderPara.getIsCancel());
                    }else{
                        sellingOrderPara.setOrderType(1);
                    }
                }
                Integer returnStatus =Integer.valueOf(sellingOrderPara.getOrderReturnStatus()) ;
                Integer refundStatus = Integer.valueOf(sellingOrderPara.getOrderRefundStatus());
                if (2 == returnStatus || 2 == refundStatus) {
                    BigDecimal returnAmount = sellingOrderPara.getOrderRefundAmount();
                    BigDecimal orderAmount = sellingOrderPara.getOrderPaymentAmount();
                    if (orderAmount.compareTo(returnAmount) > 0) {
                        returnFlag = 2;
                    } else if ((orderAmount.compareTo(returnAmount) == 0)) {
                        returnFlag = 1;
                    }
                }
                sellingOrderPara.setReturnFlag(returnFlag);
                //第三方支付金额赋值 2-支付宝支付，3-微信支付
                if ("2".equals(sellingOrderPara.getPayCode()) || "3".equals(sellingOrderPara.getPayCode())) {
                    sellingOrderPara.setTradeThirdPartyAmount(sellingOrderPara.getOrderPaymentAmount());
                } else if ("6".equals(sellingOrderPara.getPayCode())) {
                    sellingOrderPara.setTradePaymentRechargeCard(sellingOrderPara.getOrderPaymentAmount());
                }
                if (refundStatus != 0 || returnFlag != 0){
                    sellingOrderPara.setIsExistReturn("1");
                }else{
                    sellingOrderPara.setIsExistReturn("0");
                }
            }

        }
        Map<String, Object> Map = new HashMap<>();
        Map.put("orderMoney", orderMoney);
        Map.put("orderData", PageUtils.getPage(page));

        return ResponseResult.success(Map);
    }

    @Override
    public ResponseResult orderSellingTransactionExcel(SellingInputDTO sellingPara) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(sellingPara.getToken());
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(), BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }

        String[] headers = {"订单编号",  "买家账号","订单来源","下单时间","订单金额(元)","支付金额(元)",  "订单状态", "收件人姓名","联系方式",
                "收货地址","是否存在退货退款", "支付单号","支付方式", "支付方式名称", "充值卡余额支付", "第三方支付金额", "支付时间","发货时间",
                "发货物流单号","退款金额","订单完成时间","拼团状态","是否评价", "店铺ID","店铺名称","买家ID"};
        List<Map<String, String>> list = Lists.newArrayList();
        List<SellingOrderVO> records = this.baseMapper.orderSellingDaoTransactionExp(sellingPara);
        for (SellingOrderVO res : records) {
            HashMap<String, String> map = com.google.common.collect.Maps.newHashMap();
            if (res.getOrderStatus() != null) {

                switch (res.getOrderStatus()) {
                    case "1":
                        res.setOrderStatus("待付款 ");
                        break;
                    case "2":
                        res.setOrderStatus("已付款");
                        break;
                    case "3":
                        res.setOrderStatus("待发货  ");
                        break;
                    case "4":
                        res.setOrderStatus("已发货 ");
                        break;
                    case "5":
                        res.setOrderStatus("已签收 ");
                        break;
                    case "6":
                        res.setOrderStatus("确认收货");
                        break;
                    case "7":
                        res.setOrderStatus("取消 ");
                        break;
                    case "8":
                        res.setOrderStatus("退款中");
                        break;
                    case "9":
                        res.setOrderStatus("已退款 ");
                        break;
                    case "11":
                        res.setOrderStatus("待自提");
                        break;
                    case "12":
                        res.setOrderStatus("已过期");
                        break;
                }
                if (res.getOrderReturnStatus().equals("2") && res.getOrderStatus().equals("已退款 ")) {
                    res.setOrderStatus("已退货 ");
                }
            }
            if (res.getPayCode() != null) {

                switch (res.getPayCode()) {
                    // 0 无 1-余额支付，2-支付宝支付，3-微信支付，4-通联支付,5-健康账户余额支付',
                    case "0":
                        res.setPayCode("无");
                        break;
                    case "1":
                        res.setPayCode("余额支付");
                        break;
                    case "2":
                        res.setPayCode("支付宝支付");
                        break;
                    case "3":
                        res.setPayCode("微信支付");
                        break;
                    case "4":
                        res.setPayCode("通联支付");
                        break;
                    case "5":
                        res.setPayCode("健康账户余额支付 ");
                        break;
                    case "6":
                        res.setPayCode("充值卡余额支付 ");
                        break;
                    case "7":
                        res.setPayCode("充值卡+支付宝支付 ");
                        break;
                    case "8":
                        res.setPayCode("充值卡+微信 ");
                        break;
                }
            }

            if (res.getOrderFrom() != null) {

                switch (res.getOrderFrom()) {
                    //1PC 2wap微信浏览器 3安卓 5ios 6微信小程序 7wap浏览器
                    case "1":
                        res.setOrderFrom("pc");
                        break;
                    case "2":
                        res.setOrderFrom("wap微信浏览器");
                        break;
                    case "3":
                        res.setOrderFrom("安卓");
                        break;
                    case "5":
                        res.setOrderFrom("ios");
                        break;
                    case "6":
                        res.setOrderFrom("微信小程序");
                        break;
                    case "7":
                        res.setOrderFrom("wap浏览器");
                        break;
                }
            }

            if (res.getOrderRefundStatus() != null) {

                switch (res.getOrderRefundStatus()) {
                    // 0是无退款,1是退款中,2是退款完成',
                    case "0":
                        res.setOrderRefundStatus("无退款");
                        break;
                    case "1":
                        res.setOrderRefundStatus("退款中 ");
                        res.setOrderStatus("退款中 ");
                        break;
                    case "2":
                        res.setOrderRefundStatus("退款完成");
                        res.setOrderStatus("退款完成 ");
                        break;

                }
            }

            if (res.getOrderReturnStatus() != null) {

                switch (res.getOrderReturnStatus()) {
                    // 0是无退款,1是退款中,2是退款完成',
                    case "0":
                        res.setOrderReturnStatus("无退货");
                        break;
                    case "1":
                        res.setOrderReturnStatus("退货中 ");
                        res.setOrderStatus("退货中 ");
                        break;
                    case "2":
                        res.setOrderReturnStatus("退货完成");
                        res.setOrderStatus("退货完成 ");
                        break;
                }
            }
            if (res.getIsExistReturn() != null) {
                switch (res.getIsExistReturn()) {
                    case "0":
                        res.setIsExistReturn("否");
                        break;
                    case "1":
                        res.setIsExistReturn("是 ");
                        break;
                }
            }
            if (res.getOrderBuyerEvaluationStatus() != null) {
                switch (res.getOrderBuyerEvaluationStatus()) {
                    case "0":
                        res.setOrderBuyerEvaluationStatus("未评价");
                        break;
                    case "1":
                        res.setOrderBuyerEvaluationStatus("已评价 ");
                        break;
                }
            }
            if (!"".equals(res.getGroupbuyStatus()) && res.getGroupbuyStatus() != null) {
                switch (res.getGroupbuyStatus()) {
                    case "0":
                        res.setGroupbuyStatus("非拼团");
                        break;
                    case "1":
                        res.setGroupbuyStatus("拼团中");
                        break;
                    case "2":
                        res.setGroupbuyStatus("已成功");
                        break;
                    case "3":
                        res.setGroupbuyStatus("未成功");
                        break;
                }

            }
            map.put("订单编号", res.getOrderId());
            map.put("买家账号", res.getBuyerUserName());
            if ("".equals(res.getOrderFrom()) || res.getOrderFrom() == null) {
                map.put("订单来源", "无");
            } else {
                map.put("订单来源", res.getOrderFrom());
            }
            map.put("下单时间", res.getOrderCreateTime());
            map.put("订单金额(元)", res.getOrderAmount() + "");
            map.put("支付金额(元)", res.getOrderPaymentAmount() + "");
            if ("".equals(res.getOrderStatus()) || res.getOrderStatus() == null) {
                map.put("订单状态", "无");
            } else {
                map.put("订单状态", res.getOrderStatus());
            }
            if ("".equals(res.getOrderReceiverName()) || res.getOrderReceiverName() == null) {
                map.put("收件人姓名", "无");
            } else {
                map.put("收件人姓名", res.getOrderReceiverName());
            }
            map.put("联系方式", res.getOrderReceiverContact());
            map.put("收货地址", res.getOrderReceiverAddress());
            map.put("是否存在退货退款", res.getIsExistReturn());
            map.put("支付单号", res.getPaymentNumber());
            if ("".equals(res.getPaymentName()) || res.getPaymentName() == null) {
                map.put("支付方式", "无");
            } else {
                map.put("支付方式", res.getPaymentName());
            }
            if ("".equals(res.getPayCode()) || res.getPayCode() == null) {
                map.put("支付方式名称", "无");

            } else {
                map.put("支付方式名称", res.getPayCode());
            }
            map.put("充值卡余额支付", res.getTradePaymentRechargeCard() + "");
            map.put("第三方支付金额", res.getTradeThirdPartyAmount() + "");
            if ("".equals(res.getPaymentTime()) || res.getPaymentTime() == null) {
                map.put("支付时间", "无");

            } else {
                map.put("支付时间", res.getPaymentTime());
            }
            if ("".equals(res.getOrderShippingTime()) || res.getOrderShippingTime() == null) {
                map.put("发货时间", "无");
            } else {
                map.put("发货时间", res.getOrderShippingTime());
            }
            if ("".equals(res.getOrderShippingCode()) || res.getOrderShippingCode() == null) {
                map.put("发货物流单号", "无");

            } else {
                map.put("发货物流单号", res.getOrderShippingCode());
            }

            if (res.getOrderRefundAmount() == null) {
                res.setOrderRefundAmount(new BigDecimal(0));
            }
            map.put("退款金额", res.getOrderRefundAmount() + "");
            if ("".equals(res.getOrderFinishedTime()) || res.getOrderFinishedTime() == null) {
                map.put("订单完成时间", "无");

            } else {
                map.put("订单完成时间", res.getOrderFinishedTime());
            }
            map.put("拼团状态", res.getGroupbuyStatus());
            map.put("是否评价", res.getOrderBuyerEvaluationStatus());
            map.put("店铺ID", res.getShopId() + "");
            map.put("店铺名称", res.getShopName());
            map.put("买家ID", res.getBuyerUserId() + "");
            list.add(map);
        }

        // excel文件名
        Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
         * 该list为每个sheet页的数据
         */> map = Maps
                .newHashMap();
        map.put("订单明细", list);
        String url = ExcelsUtil.createExcel(headers, map, new int[]{0}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);

        return ResponseResult.success(url);
    }

    @Override
    public ResponseResult PlatFormBackGroundByOrderDetails(Map<String, Object> buyingPara) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(String.valueOf(buyingPara.get("token")));
        if (userInfo == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        String orderId = (String) buyingPara.get("orderId");
        if (com.yuanfeng.commoms.util.StringUtils.isEmpty(orderId)) {
            return ResponseResult.fail(BizCodeEnume.MISSING_PARAMETER);
        } else {
            OrderbaseDetailsparaVO param = this.baseMapper.queryorderDetailparam(orderId);
            List<GoodsAllByidVO> res = this.baseMapper.getGoodsAllByIdparam(orderId);
            Integer returnFlag = 0;
            Integer virtualGoods = param.getVirtualGoods();
            Integer orderIsShopTake = param.getOrderIsShopTake();
            if (null != orderIsShopTake && 1 == orderIsShopTake) {
                param.setOrderType(3);
            } else {
                if (null != virtualGoods && 0 == virtualGoods) {
                    param.setOrderType(2);
                    param.setPastDue(param.getPastDue());
                    param.setIsCancel(param.getIsCancel());
                } else {
                    param.setOrderType(1);
                }
            }
            int returnStatus = param.getOrderReturnStatus();
            int refundStatus = param.getOrderRefundStatus();
            param.setReturnStatus(returnStatus);
            param.setRefundStatus(refundStatus);
            if (2 == returnStatus || 2 == refundStatus) {
                BigDecimal returnAmount = param.getOrderRefundAmount();
                BigDecimal orderAmount = BigDecimal.valueOf(param.getOrderPaymentAmount());
                if (orderAmount.compareTo(returnAmount) > 0) {
                    returnFlag = 2;
                } else if ((orderAmount.compareTo(returnAmount) == 0)) {
                    returnFlag = 1;
                }
            }
            //商品总件数
            Integer goodsNum = 0;
            //平台总优惠
            BigDecimal totalPlatformDiscount = new BigDecimal(0);
            //商家总优惠
            BigDecimal totalMerchantDiscount = new BigDecimal(0);
            //预计获得的积分
            Integer pointsObtained = 0;
            //查询积分规则
            ResponseResult resultResp = baseServiceClient.queryIntegralRules();
            Map<String, Integer> integralRules = (Map<String, Integer>) resultResp.getData();
            param.setReturnFlag(returnFlag);
            for (GoodsAllByidVO pa : res) {
                if (pa.getGoodsRefundStatus() == 0) {
                    pa.setIsNoretrun(0);
                } else {
                    pa.setIsNoretrun(1);
                }
                goodsNum = goodsNum + pa.getOrderGoodsNum();
                if(null != pa.getVoucherPrice()){
                    totalMerchantDiscount = totalPlatformDiscount.add(pa.getVoucherPrice());
                }
                if(null != pa.getOrderRptPrice()){
                    totalPlatformDiscount = totalMerchantDiscount.add(pa.getOrderRptPrice());
                }
                if(null != pa.getGoodsPlusDiscount()){
                    totalPlatformDiscount = totalMerchantDiscount.add(pa.getGoodsPlusDiscount());
                }
                if(null != pa.getGoodsMemberDiscount()){
                    totalPlatformDiscount = totalMerchantDiscount.add(pa.getGoodsMemberDiscount());
                }
            }
            if(null != integralRules.get("ruleConsume")){
                double pointsObtained2 =  param.getOrderPaymentAmount()*integralRules.get("ruleConsume");
                BigDecimal bd = new BigDecimal(pointsObtained2).setScale(0, BigDecimal.ROUND_HALF_UP);
                pointsObtained = Integer.parseInt(bd.toString());
            }
            param.setGoodsNum(goodsNum);
            param.setTotalPlatformDiscount(totalPlatformDiscount);
            param.setTotalMerchantDiscount(totalMerchantDiscount);
            param.setPointsObtained(pointsObtained);
            param.setGoodsAllByidParam(res);
            //获取支付凭证信息
            OdbPaymentVocherVO odbPaymentVocher = this.baseMapper.queryPaymentVocher(orderId);
            if (null != odbPaymentVocher) {
                param.setOdbPaymentVocherPO(odbPaymentVocher);
            }
            return ResponseResult.success(param);
        }
    }

    @Override
    public ResponseResult PlatFormBackGroundBySelling(SellingInputDTO sellingPara) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(sellingPara.getToken());
        if (userInfo == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        Map data = null;
        try {
            data = ParseMapUtils.beanToMap(sellingPara);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        IPage<SellingOrderVO> page = this.baseMapper.selectSellingOrder(new Query<SellingOrderVO>().getPage(data), sellingPara);
        BigDecimal orderMoney = this.baseMapper.querySellingOrderMoney(sellingPara);

        Map<String, Object> map = new HashMap<>();
        map.put("orderMoney", orderMoney);
        map.put("orderData", PageUtils.getPage(page));
        return ResponseResult.success(map);

    }

    @Override
    public ResponseResult PlatFormBackGroundBySellingExp(SellingInputDTO sellingPara) {

        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(sellingPara.getToken());
        if (userInfo == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        Page<SellingOrderVO> page = new Page<>(0,-1);
        String[] headers = {"订单编号", "订单来源", "审核状态", "买家账号", "下单时间", "订单金额(元)", "支付金额(元)",
                "收件人姓名", "联系方式", "收货地址", "支付单号", "店铺名称"};
        List<Map<String, String>> list = Lists.newArrayList();
        IPage<SellingOrderVO> result = this.baseMapper.selectSellingOrder(page, sellingPara);
        for (SellingOrderVO res : result.getRecords()) {
            HashMap<String, String> map = com.google.common.collect.Maps.newHashMap();
            if (res.getOrderFrom() != null) {
                switch (res.getOrderFrom()) {
                    //1PC 2wap微信浏览器 3安卓 5ios 6微信小程序 7wap浏览器
                    case "1":
                        res.setOrderFrom("pc");
                        break;
                    case "2":
                        res.setOrderFrom("wap微信浏览器");
                        break;
                    case "3":
                        res.setOrderFrom("安卓");
                        break;
                    case "5":
                        res.setOrderFrom("ios");
                        break;
                    case "6":
                        res.setOrderFrom("微信小程序");
                        break;
                    case "7":
                        res.setOrderFrom("wap浏览器");
                        break;
                }
            }
            String reviewStr = null;
            if (res.getReviewStatus() != null) {
                switch (res.getReviewStatus()) {
                    case 1:
                        reviewStr = "待审核";
                        break;
                    case 2:
                        reviewStr = "审核已通过";
                        break;
                    case 3:
                        reviewStr = "审核已驳回";
                        break;
                }
            } else {
                reviewStr = "待上传支付凭证";
            }
            map.put("订单编号", res.getOrderId());
            if ("".equals(res.getOrderFrom()) || res.getOrderFrom() == null) {
                map.put("订单来源", "无");
            } else {
                map.put("订单来源", res.getOrderFrom());
            }
            map.put("审核状态", reviewStr);
            map.put("买家账号", res.getBuyerUserName());
            if (res.getOrderRefundAmount() == null) {
                res.setOrderRefundAmount(new BigDecimal(0));
            }
            map.put("下单时间", res.getOrderCreateTime());
            map.put("订单金额(元)", res.getOrderAmount() + "");
            map.put("支付金额(元)", res.getOrderPaymentAmount() + "");
            if ("".equals(res.getOrderReceiverName()) || res.getOrderReceiverName() == null) {
                map.put("收件人姓名", "无");
            } else {
                map.put("收件人姓名", res.getOrderReceiverName());
            }
            map.put("联系方式", res.getOrderReceiverContact());
            map.put("收货地址", res.getOrderReceiverAddress().trim());
            map.put("支付单号", res.getPaymentNumber());
            map.put("店铺名称", res.getShopName());

            list.add(map);
        }

        // excel文件名
        Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
         * 该list为每个sheet页的数据
         */> map = Maps.newHashMap();
        map.put("测试合并数据", list);
        String url = ExcelsUtil.createExcel(headers, map, new int[]{0}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);
        return ResponseResult.success(url);
    }

    @Override
    public ResponseResult overTimeReturnOrder(Map<String, String> paraMap) throws ParseException {
        Date orderFinishTime = this.baseMapper.selectById(new LambdaQueryWrapper<OrderBaseEntity>()
                .eq(OrderBaseEntity::getOrderStatus, CommonType.orderStatus.CONFIRM_RECEIPT.getCode())
                .isNotNull(OrderBaseEntity::getOrderFinishedTime)
                .eq(OrderBaseEntity::getOrderId, paraMap.get("orderId"))).getOrderFinishedTime();
        if (orderFinishTime == null) {
            return ResponseResult.fail(BizCodeEnume.VALID_EXCEPTION);
        }
        Date date2 = DateUtils.getNowDateToDf();
        boolean latestWeek = DateUtils.isLatestWeek(orderFinishTime, date2);
        if (latestWeek) {
            return ResponseResult.success(BizCodeEnume.NOT_EXCEEDING_THE_TIME_AFTER_SALE);
        } else {
            return ResponseResult.fail(BizCodeEnume.ORDER_AFTER_TIME_EXCEED);
        }
    }

    @Override
    public ResponseResult queryLogistics2(Map<Object, Object> map) {
        String token = map.get("token").toString();
        UserInfoVO userInfoVO = ParseTokenUtils.getUserInfoByToken(token);
        if (userInfoVO == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        //物流信息
        Map<String, String> shippingMap = new HashMap<>();
        List<Map<String, String>> returnStrs = new ArrayList<>();
        // 物流信息
        String returnStr = null;
        try {
            String shippingCode = map.get("no").toString();
            String orderId = map.get("orderId").toString();
            List<LogisticsMessageVO> shippingList = this.baseMapper.queryLogisticsMessage(orderId);
            log.info("---------开始查询运单号为{}的物流信息", shippingCode);
            Map<String, String> resultMap = getShipperCode2(shippingCode, orderId, token);
            //获取快递鸟的配置信息
            KdniaoTrackQueryAPI.AppKey = resultMap.get("AppKey");
            KdniaoTrackQueryAPI.EBusinessID = resultMap.get("EBussinessID");
            KdniaoTrackQueryAPI.instructCode = String.valueOf(resultMap.get("instructCode"));
            //获取快递的简称
            String shipperCode = resultMap.get("shipperCode");
            //获取收件人手机号后四位
            String customerName = resultMap.get("customerName");

            returnStr = KdniaoTrackQueryAPI.getOrderTracesByJson(shipperCode, shippingCode, customerName);

            if (org.apache.commons.lang.StringUtils.isNotEmpty(returnStr)) {
                shippingMap.put("shippingInfo", returnStr);
                shippingMap.put("expressName", resultMap.get("expressName"));
                shippingMap.put("shippingCode", shippingCode);
                shippingMap.put("orderShippingMessage", shippingList.get(0).getOrderShippingMessage());
                shippingMap.put("orderReceiverName", shippingList.get(0).getOrderReceiverName());
                shippingMap.put("orderReceiverAddress", shippingList.get(0).getOrderReceiverAddress());
                shippingMap.put("orderReceiverContact", shippingList.get(0).getOrderReceiverContact());
                returnStrs.add(shippingMap);
            }

            log.info("---------查询运单号为{}的物流信息结束,物流信息：{}", shippingCode, returnStr);
        } catch (Exception e) {
            return ResponseResult.fail(e.getMessage());
        }
        return ResponseResult.success(returnStrs);
    }

    @Override
    public ResponseResult querkVocherImages(QukVocherImagesDTO param) {
        OdbPaymentVocherVO PaymentVocherPo = this.baseMapper.queryPaymentVocher(param.getOrderId());
        if (null != PaymentVocherPo) {
            return ResponseResult.success(PaymentVocherPo);
        } else {
            return ResponseResult.fail();
        }
    }

    @Override
    public ResponseResult checkPaymentVocher(QukVocherImagesDTO param) {
        HashMap<Object, Object> map = new HashMap<>();
        Integer integer = 0;
        if (param.getReviewStatus() == 2) {
            map.put("orderIdList", param.getOrderId());
            ResponseResult results = payMentServiceClient.checkPaymentVocher(map);
            if (results.getCode() == 1) {
                integer = this.baseMapper.updatePaymentVocher(param);
            }

        } else {
            integer = this.baseMapper.updatePaymentVocher(param);
        }
        if (integer > 0) {
            return ResponseResult.success();
        }
        return ResponseResult.fail();
    }

    @Override
    public ResponseResult isVirtualOrder(Map<String, String> orderIdIsNum) {
        String orderid = orderIdIsNum.get("orderId");
        String isNum = orderIdIsNum.get("isNum");
        Map<String, Object> map = null;
        //0 是数字订单 1 不是数字订单
        if ("0".equals(isNum)) {
            map = this.baseMapper.queryisVirtualOrder(orderid, 0);
        } else {
            map = this.baseMapper.queryisVirtualOrder(orderid, 1);
        }
        return ResponseResult.success(map);
    }

    @Override
    public ResponseResult addRedeemCode(Map<String, Object> param) {
        Integer integer = this.baseMapper.addRedeemCode(param);
        if (integer > 0) {
            return ResponseResult.success();
        }
        return ResponseResult.fail();
    }

    @Override
    public ResponseResult orderToInform(Map<String, Object> map) {
        // 支付号
        String payNumber = (String) map.get("orderId");
        String paymentTime = (String) map.get("paymentTime");
        boolean isInsertSuccess = false;
        if (MathUtil.isInteger(payNumber)) {
            // 判断是否是纯数字订单
            OrderToInformParaVO orderToInform = this.baseMapper.queryBaseParaByInt(payNumber);
            String orderId = orderToInform.getOrderId();
            String sellerId = orderToInform.getSellerUserId();
            String sellerName = orderToInform.getSellerUserName();
            String shopId = orderToInform.getShopId();
            Integer messageType = 1;
            String messageTitle = "下单通知";
            String messageCreateTime = DateUtils.getTime();
            String messageContent = "您的会员" + orderToInform.getBuyerUserName() + "在" + paymentTime + "提交了订单" + orderId + ",请尽快发货！";
            isInsertSuccess = this.baseMapper.insertSysMessage(orderId, sellerId, sellerName, messageType, messageTitle,
                    messageCreateTime, messageContent, shopId);
        } else {
            List<OrderToInformParaVO> orderToInformList = this.baseMapper.queryBasePara(payNumber);
            for (int i = 0; i < orderToInformList.size(); i++) {
                String orderId = orderToInformList.get(i).getOrderId();
                String sellerId = orderToInformList.get(i).getSellerUserId();
                String sellerName = orderToInformList.get(i).getSellerUserName();
                String shopId = orderToInformList.get(i).getShopId();
                Integer messageType = 1;
                String messageTitle = "下单通知";
                String messageCreateTime = DateUtils.getTime();
                String messageContent = "您的会员" + orderToInformList.get(i).getBuyerUserName() + "在" + paymentTime + "提交了订单" + orderId + ",请尽快发货！";
                isInsertSuccess = this.baseMapper.insertSysMessage(orderId, sellerId, sellerName, messageType, messageTitle,
                        messageCreateTime, messageContent, shopId);
            }
        }
        if (isInsertSuccess) {
            return ResponseResult.success();
        } else {
            return ResponseResult.fail();
        }
    }

    @Override
    public ResponseResult queryUpayByOrderId(String order_id) {
        String s = this.baseMapper.queryUpayByOrderId(order_id);
        return ResponseResult.success(s);
    }

    @Override
    public ResponseResult PlatFormOfflineOrderEXcel(SellingInputDTO sellingInputDTO) throws ParseException {
        String userInfoStr = RedisUtil.get(YFConfig.YF_PLATFORM_TOKEN_USER + sellingInputDTO.getToken());
        if (null == userInfoStr || userInfoStr.equals("")) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }

        Integer type = Integer.valueOf(sellingInputDTO.getType());
        String allOrderType = null;
        Integer otherOrderType = null;
        // 判断状态
        if (type == 1) {
            // 全部订单
            allOrderType = "' '";
        } else if (type == 2) {
            // 待付款订单
            otherOrderType = 1;
        } else if (type == 3) {
            // 已付款待发货订单
            otherOrderType = 3;
        } else if (type == 4) {
            // 已发货订单
            otherOrderType = 4;
        } else if (type == 5) {
            // 已完成订单
            otherOrderType = 6;
        } else if (type == 6) {
            // 已取消订单
            otherOrderType = 7;
        } else if (type == 7) {
            otherOrderType = 0;
        } else if (type == 8) {
            // 待审核上传支付凭证
            otherOrderType = 11;
        } else if (type == 9) {
            // 已审核上传支付凭证
            otherOrderType = 12;
        } else if (type == 10) {
            // 已驳回上传支付凭证
            otherOrderType = 13;
        } else if (type == 11) {
//				otherOrderType=14;//释放这一行，即查询出所有已上传支付凭证的线下订单
        }


        Map<Object, Object> mapobject = new HashMap<Object, Object>();
        mapobject.put("orderId", sellingInputDTO.getOrderId());
        mapobject.put("buyerUserName", sellingInputDTO.getBuyerUserName()==null?"":sellingInputDTO.getBuyerUserName());
        mapobject.put("shopName", sellingInputDTO.getShopName()==null?"":sellingInputDTO.getShopName());
        mapobject.put("paymentNo", sellingInputDTO.getPaymentNo());
        mapobject.put("allOrderType", allOrderType);
        mapobject.put("otherOrderType", otherOrderType);
        mapobject.put("airTime", sellingInputDTO.getStartTime());
        mapobject.put("finishTime", sellingInputDTO.getEndTime());
        //省id
        mapobject.put("provinceId", sellingInputDTO.getProvinceId());
        //市Id
        mapobject.put("cityId", sellingInputDTO.getDistrictCityId());
        //区id
        mapobject.put("districtId", sellingInputDTO.getAreaId());


        List<SellingOrderVO> sellingList = this.baseMapper.PlatFormOfflineOrderEXcel(mapobject);
        String[] headers = {"订单编号", "订单来源", "审核状态", "买家账号", "下单时间", "订单金额(元)", "支付金额(元)", "收货人名称", "联系方式", "收货地址", "支付单号",
                "店铺名称"};
        List<Map<String, String>> list = Lists.newArrayList();
        ResponseResult resp = new ResponseResult();
        for (SellingOrderVO res : sellingList) {
            HashMap<String, String> map = Maps.newHashMap();
            map.put("订单编号", res.getOrderId());
            if (res.getOrderFrom() != null) {

                switch (res.getOrderFrom()) {
                    //1PC 2wap微信浏览器 3安卓 5ios 6微信小程序 7wap浏览器
                    case "1":
                        res.setOrderFrom("pc");
                        break;
                    case "2":
                        res.setOrderFrom("wap微信浏览器");
                        break;
                    case "3":
                        res.setOrderFrom("安卓");
                        break;
                    case "5":
                        res.setOrderFrom("ios");
                        break;
                    case "6":
                        res.setOrderFrom("微信小程序");
                        break;
                    case "7":
                        res.setOrderFrom("wap浏览器");
                        break;
                }
            }
            map.put("订单来源", res.getOrderFrom());
            if (res.getReviewStatus() != null) {

                switch (res.getReviewStatus()) {
                    //审核状态  0 待上传   1 待审核 2 已审核 3 审核驳回
                    case 0:
                        map.put("审核状态", "待上传");
                        break;
                    case 1:
                        map.put("审核状态", "待审核");
                        break;
                    case 2:
                        map.put("审核状态", "已审核");
                        break;
                    case 3:
                        map.put("审核状态", "审核驳回");
                        break;
                }
            } else {
                map.put("审核状态", "无");
            }
            map.put("买家账号", res.getBuyerUserName());
            map.put("下单时间", res.getOrderCreateTime());
            map.put("订单金额(元)", res.getOrderAmount() + "");
            map.put("支付金额(元)", res.getOrderPaymentAmount() + "");
            map.put("收货人名称", res.getOrderReceiverName());
            map.put("收货地址", res.getOrderReceiverAddress());
            map.put("联系方式", res.getOrderReceiverContact());
            map.put("支付单号", res.getPaymentNumber());
            map.put("店铺名称", res.getShopName());
            list.add(map);
        }
        // excel文件名
        Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
         * 该list为每个sheet页的数据
         */> map = Maps
                .newHashMap();
        map.put("测试合并数据", list);
        String url = ExcelsUtil.createExcel(headers, map, new int[]{0}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);
        resp.setCode(1);
        resp.setData(url);
        return resp;
    }

    @Override
    public ResponseResult PlatFormBackGroundBySellingNew(SellingInputNewDTO sellingPara) throws ParseException, IllegalAccessException {

        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(sellingPara.getToken());

        if (checkLimit("orderList", userInfo)) {
            //实物订单
            if (null != sellingPara.getOrderType() && 1 == sellingPara.getOrderType()) {
                //虚拟订单 0 是 1 否
                sellingPara.setVirtualGoods(1);
                //门店自提订单 1是 2否
                sellingPara.setOrderIsShopTake(2);
                //虚拟订单（不包含门店虚拟订单）
            } else if (null != sellingPara.getOrderType() && 2 == sellingPara.getOrderType()) {
                //虚拟订单 0 是 1 否
                sellingPara.setVirtualGoods(0);
                //门店自提订单 1是 2否
                sellingPara.setOrderIsShopTake(2);
                //门店订单（包含门店虚拟订单）
            } else if (null != sellingPara.getOrderType() && 3 == sellingPara.getOrderType()) {
                //门店自提订单 1是 2否
                sellingPara.setOrderIsShopTake(1);
            }
            if (null != sellingPara.getOrderStatus() && sellingPara.getOrderStatus().equals(3)) {
                // 已付款待发货订单
                sellingPara.setReturnStatus(0);
                sellingPara.setRefundStatus(0);
            } else if (null != sellingPara.getOrderStatus() && sellingPara.getOrderStatus().equals(4)) {
                // 已发货订单
                sellingPara.setReturnStatus(0);
                sellingPara.setRefundStatus(0);
            } else if (null != sellingPara.getOrderStatus() && sellingPara.getOrderStatus().equals(6)) {
                // 已完成订单
                sellingPara.setReturnStatus(0);
                sellingPara.setRefundStatus(0);
            } else if (null != sellingPara.getOrderStatus() && sellingPara.getOrderStatus().equals(8)) {
                // 退货中
                sellingPara.setOrderStatus(null);
                sellingPara.setReturnStatus(1);
            } else if (null != sellingPara.getOrderStatus() && sellingPara.getOrderStatus().equals(9)) {
                // 退款中
                sellingPara.setOrderStatus(null);
                sellingPara.setRefundStatus(1);
            } else if (null != sellingPara.getOrderStatus() && sellingPara.getOrderStatus().equals(10)) {
                // 退款完成
                sellingPara.setOrderStatus(null);
                sellingPara.setRefundStatus(2);
            } else if (null != sellingPara.getOrderStatus() && sellingPara.getOrderStatus().equals(11)) {
                // 退货完成
                sellingPara.setOrderStatus(null);
                sellingPara.setReturnStatus(2);
            }
            Map data = ParseMapUtils.beanToMap(sellingPara);
            IPage<SellingOrderVO> page = this.baseMapper.selectSellingOrderNew2(new Query<SellingOrderVO>().getPage(data),
                    sellingPara);
            String orderMoney = this.baseMapper.querySellingOrderMoneynNew2(sellingPara);
            if (orderMoney == null) {
                orderMoney = "0";
            }
            Integer returnFlag = 0;
            if (null != page.getRecords() && page.getRecords().size() > 0) {
                for (SellingOrderVO sellingOrderPara : page.getRecords()) {
                    Integer virtualGoods = sellingOrderPara.getVirtualGoods();
                    Integer orderIsShopTake = sellingOrderPara.getOrderIsShopTake();
                    if (null != orderIsShopTake && 1 == orderIsShopTake) {
                        sellingOrderPara.setOrderType(3);
                    } else {
                        if (null != virtualGoods && 0 == virtualGoods) {
                            sellingOrderPara.setOrderType(2);
                            sellingOrderPara.setPastDue(sellingOrderPara.getPastDue());
                            sellingOrderPara.setIsCancel(sellingOrderPara.getIsCancel());
                        } else {
                            sellingOrderPara.setOrderType(1);
                        }
                    }
                    Integer returnStatus = Integer.valueOf(sellingOrderPara.getOrderReturnStatus());
                    Integer refundStatus = Integer.valueOf(sellingOrderPara.getOrderRefundStatus());
                    if (2 == returnStatus || 2 == refundStatus) {
                        BigDecimal returnAmount = sellingOrderPara.getOrderRefundAmount();
                        BigDecimal orderAmount = sellingOrderPara.getOrderPaymentAmount();
                        if (orderAmount.compareTo(returnAmount) > 0) {
                            returnFlag = 2;
                        } else if ((orderAmount.compareTo(returnAmount) == 0)) {
                            returnFlag = 1;
                        }
                    }
                    sellingOrderPara.setReturnFlag(returnFlag);
                    //第三方支付金额赋值 2-支付宝支付，3-微信支付
                    if ("2".equals(sellingOrderPara.getPayCode()) || "3".equals(sellingOrderPara.getPayCode())) {
                        sellingOrderPara.setTradeThirdPartyAmount(sellingOrderPara.getOrderPaymentAmount());
                    } else if ("6".equals(sellingOrderPara.getPayCode())) {
                        sellingOrderPara.setTradePaymentRechargeCard(sellingOrderPara.getOrderPaymentAmount());
                    }
                    if (0 != returnStatus && 0 != refundStatus) {
                        sellingOrderPara.setIsExistReturn("1");
                    } else {
                        sellingOrderPara.setIsExistReturn("0");
                    }
                }

            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("orderMoney",orderMoney);
            map.put("data",PageUtils.getPage(page));
            return ResponseResult.success(map);
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
    }

    @Override
    public ResponseResult platFormOnlineOrdersEXcel(SellingInputNewDTO sellingPara) {
        UserInfoVO userInfoVO = ParseTokenUtils.getPlatformUser(sellingPara.getToken());
        if (null == userInfoVO ) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }

        String[] headers = {"订单编号","订单来源", "付款来源", "买家账号", "下单时间", "订单金额(元)", "支付金额(元)", "订单状态",
                "收件人姓名", "联系方式", "收货地址", "是否存在退货退款", "支付单号", "第三方支付单号", "支付方式", "充值卡余额支付",
                "第三方支付金额", "支付时间", "发货物流单号", "退款金额", "订单完成时间", "是否拼团", "是否评价", "店铺名称"};
        List<Map<String, String>> list = Lists.newArrayList();

        List<SellingOrderVO> result = this.baseMapper.selectSellingOrderNewEXcel(sellingPara);

        for (SellingOrderVO res : result) {
            HashMap<String, String> map = com.google.common.collect.Maps.newHashMap();
            if (res.getOrderStatus() != null) {
                switch (res.getOrderStatus()) {
                    case "1":
                        res.setOrderStatus("待付款 ");
                        break;
                    case "2":
                        res.setOrderStatus("已付款");
                        break;
                    case "3":
                        res.setOrderStatus("待发货  ");
                        break;
                    case "4":
                        res.setOrderStatus("已发货 ");
                        break;
                    case "5":
                        res.setOrderStatus("已签收 ");
                        break;
                    case "6":
                        res.setOrderStatus("确认收货");
                        break;
                    case "7":
                        res.setOrderStatus("取消 ");
                        break;
                    case "8":
                        res.setOrderStatus("退款中");
                        break;
                    case "9":
                        res.setOrderStatus("已退款 ");
                        break;
                    case "11":
                        res.setOrderStatus("待自提");
                        break;
                    case "12":
                        res.setOrderStatus("已过期");
                        break;
                }
                if (res.getOrderReturnStatus().equals("2") && res.getOrderStatus().equals("已退款 ")){
                    res.setOrderStatus("已退货 ");
                }
            }
            if (res.getPayCode() != null) {

                switch (res.getPayCode()) {
                    // 0 无 1-余额支付，2-支付宝支付，3-微信支付，4-通联支付,5-健康账户余额支付',
                    case "0":
                        res.setPayCode("无");
                        break;
                    case "1":
                        res.setPayCode("余额支付");
                        break;
                    case "2":
                        res.setPayCode("支付宝支付");
                        break;
                    case "3":
                        res.setPayCode("微信支付");
                        break;
                    case "4":
                        res.setPayCode("通联支付");
                        break;
                    case "5":
                        res.setPayCode("健康账户余额支付 ");
                        break;
                    case "6":
                        res.setPayCode("充值卡余额支付 ");
                        break;
                    case "7":
                        res.setPayCode("充值卡+支付宝支付 ");
                        break;
                    case "8":
                        res.setPayCode("充值卡+微信 ");
                        break;
                }
            }

            if (res.getOrderFrom() != null) {

                switch (res.getOrderFrom()) {
                    //1PC 2wap微信浏览器 3安卓 5ios 6微信小程序 7wap浏览器
                    case "1":
                        res.setOrderFrom("pc");
                        break;
                    case "2":
                        res.setOrderFrom("wap微信浏览器");
                        break;
                    case "3":
                        res.setOrderFrom("安卓");
                        break;
                    case "5":
                        res.setOrderFrom("ios");
                        break;
                    case "6":
                        res.setOrderFrom("微信小程序");
                        break;
                    case "7":
                        res.setOrderFrom("wap浏览器");
                        break;
                }
            }

            if (res.getOrderRefundStatus() != null) {

                switch (res.getOrderRefundStatus()) {
                    // 0是无退款,1是退款中,2是退款完成',
                    case "0":
                        res.setOrderRefundStatus("无退款");
                        break;
                    case "1":
                        res.setOrderRefundStatus("退款中 ");
                        res.setOrderStatus("退款中 ");
                        break;
                    case "2":
                        res.setOrderRefundStatus("退款完成");
                        res.setOrderStatus("退款完成 ");
                        break;

                }
            }

            if (res.getOrderReturnStatus() != null) {

                switch (res.getOrderReturnStatus()) {
                    // 0是无退款,1是退款中,2是退款完成',
                    case "0":
                        res.setOrderReturnStatus("无退货");
                        break;
                    case "1":
                        res.setOrderReturnStatus("退货中 ");
                        res.setOrderStatus("退货中 ");
                        break;
                    case "2":
                        res.setOrderReturnStatus("退货完成");
                        res.setOrderStatus("退货完成 ");
                        break;
                }
            }
            if (res.getIsExistReturn() != null) {
                switch (res.getIsExistReturn()) {
                    case "0":
                        res.setIsExistReturn("否");
                        break;
                    case "1":
                        res.setIsExistReturn("是 ");
                        break;
                }
            }
            if (res.getOrderBuyerEvaluationStatus() != null) {
                switch (res.getOrderBuyerEvaluationStatus()) {
                    case "0":
                        res.setOrderBuyerEvaluationStatus("未评价");
                        break;
                    case "1":
                        res.setOrderBuyerEvaluationStatus("已评价 ");
                        break;
                }
            }
            if (!"".equals(res.getGroupbuyStatus()) && res.getGroupbuyStatus()!=null) {
                switch (res.getGroupbuyStatus()) {
                    case "0":
                        res.setGroupbuyStatus("非拼团");
                        break;
                    case "1":
                        res.setGroupbuyStatus("拼团中");
                        break;
                    case "2":
                        res.setGroupbuyStatus("已成功");
                        break;
                    case "3":
                        res.setGroupbuyStatus("未成功");
                        break;
                }

            }
            map.put("订单编号", res.getOrderId());
            map.put("订单来源", res.getOrderFrom() == null ? "无" : res.getOrderFrom());
            map.put("付款来源", res.getPayCode());
            map.put("买家账号", res.getBuyerUserName());
            map.put("下单时间", res.getOrderCreateTime());
            map.put("订单金额(元)", res.getOrderAmount() + "");
            map.put("支付金额(元)", res.getOrderPaymentAmount() + "");
            map.put("订单状态", res.getOrderStatus() == null ? "无" : res.getOrderStatus());
            map.put("收件人姓名", res.getOrderReceiverName() == null ? "无" : res.getOrderReceiverName());
            map.put("联系方式", res.getOrderReceiverContact());
            map.put("收货地址", res.getOrderReceiverAddress());
            map.put("是否存在退货退款", res.getIsExistReturn());
            map.put("支付单号", res.getPaymentNumber());
            map.put("第三方单号", res.getPaymentOtherNumber());
            map.put("支付方式", res.getPaymentName() == null ? "无" : res.getPaymentName());
            map.put("充值卡余额支付", res.getTradePaymentRechargeCard() + "");
            map.put("第三方支付金额", res.getTradeThirdPartyAmount() + "");
            map.put("支付时间", res.getPaymentTime() == null ? "无" : res.getPaymentTime());
            map.put("发货物流单号", res.getOrderShippingCode() == null ? "无" : res.getOrderShippingCode());
            map.put("退款金额", res.getOrderRefundAmount() == null ? "0.00" : res.getOrderRefundAmount().toString());
            map.put("订单完成时间", res.getOrderFinishedTime() == null ? "无" : res.getOrderFinishedTime());
            map.put("是否拼团", res.getGroupbuyStatus());
            map.put("是否评价", res.getOrderBuyerEvaluationStatus());
            map.put("店铺名称", res.getShopName());
            list.add(map);
        }

        // excel文件名
        Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
         * 该list为每个sheet页的数据
         */> map = Maps
                .newHashMap();
        map.put("全部订单", list);
        String url = ExcelsUtil.createExcel(headers, map, new int[]{0}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);
        return ResponseResult.success(url);
    }

    @Override
    public ResponseResult selectOrderInfoById(String OrderId) {
        OrderBaseEntity entity = this.baseMapper.selectById(OrderId);
        OrderBaseVO vo = new OrderBaseVO();
        BeanUtils.copyProperties(entity, vo);
        return ResponseResult.success(vo);
    }

    private List<String> getEmployees(UserInfoVO ui, String userId, String buyUserId) {
        List<String> userIdList = new ArrayList<>();
        if (buyUserId != null && !"0".equals(buyUserId)) {
            userIdList.add(buyUserId);
        } else {
            userIdList.add(userId);
            ResponseResult detail = userServiceClient.queryBusiness(userId);
            Map<String, Object> map = (Map<String, Object>) detail.getData();

            if (map != null && ui.getIsEmployee() != null && ui.getIsEmployee() != 1 && ui.getIsBusiness() == 1) {
                List<String> list = userServiceClient.queryEmployeesList(map.get("businessId").toString());
                if (list.contains(userId)) {
                    userIdList = list;
                }
            }
        }
        return userIdList;

    }

    @Override
    public ResponseResult UpdateOrderBaseByPayment(Map<String, Object> map) {
        // 支付订单号
        String paymentNumbers = (String) map.get("payOrderId");
        Integer type =Integer.valueOf(map.get("type").toString());
        Integer payCode = null;
        switch (type) {
            case 1:
                payCode = 1;
                break;
            case 2:
                payCode = 6;
                break;
            case 3:
                payCode = 9;
                break;
            case 6:
                payCode = 3;//微信支付
                break;
            case 12:
                payCode = 12;//线下支付 上传凭证
                break;
        }
        boolean isUpdateBaseSuccess = false;
        boolean isUpdateGoodsSuccess = false;
        boolean flag = false;
        // 支付方式
        Integer paymentId = (Integer) map.get("paymentId");
        // 支付方式名称
        String paymentName = (String) map.get("paymentName");
        // 支付时间
        String paymentTime = (String) map.get("paymentTime");

        // 支付订单信息
        List<String> orderIdList = new ArrayList<>();
        //虚拟订单 0 是 1 否
        Integer virtualGoods = (Integer) map.get("virtualGoods");
        //门店订单 1 是 2 否
        Integer orderIsShopTake = (Integer) map.get("orderIsShopTake");
        //3.待发货 4.已发货
        Integer orderStatus = 3;
        //虚拟订单 0 是 1 否
        if (null != virtualGoods && 0 == virtualGoods) {
            orderStatus = 4;
        }
        //门店订单 1 是 2 否
        if (null != orderIsShopTake && 1 == orderIsShopTake) {
            orderStatus = 4;
        }
        if (MathUtil.isInteger(paymentNumbers)) {
            isUpdateBaseSuccess = this.baseMapper.updateOrderBaseByPaymentByPureDigital(orderStatus, paymentId, paymentName, paymentTime,
                    paymentNumbers, payCode);

            orderIdList.add(paymentNumbers);
            isUpdateGoodsSuccess = orderGoodsMapper.updateOrderGoodsByStatusByPureDigital(orderStatus, paymentNumbers);
            flag = isUpdateBaseSuccess && isUpdateGoodsSuccess;
        } else {
            isUpdateBaseSuccess = this.baseMapper.updateOrderBaseByPayment(orderStatus, payCode, paymentId, paymentName, paymentTime,
                    paymentNumbers);
            // 获取实际支付单号
            orderIdList = this.baseMapper.queryActualOrderId(paymentNumbers);
            for (String orderNumber : orderIdList) {
                // 实际订单号
                isUpdateGoodsSuccess = orderGoodsMapper.updateOrderGoodsByStatus(orderStatus, orderNumber);
            }
            flag = isUpdateBaseSuccess && isUpdateGoodsSuccess;
        }
        //分佣订单更新
        Runnable fxThread = new FxThread(fxService, orderIdList);
        Thread thread = new Thread(fxThread);
        thread.start();

        return ResponseResult.success(flag);
    }

    @Override
    public boolean fiveUpdateOrderBaseByPayment(Map<Object, Object> map) {
        // 商户订单号
        String paymentNumber = (String) map.get("paymentNumber");
        boolean flag = false;
        Integer payCode = (Integer) map.get("payCode");
        Integer orderStatus = (Integer) map.get("orderStatus");
        // 支付方式
        Integer paymentId = (Integer) map.get("paymentId");
        // 支付方式名称
        String paymentName = (String) map.get("paymentName");
        // 支付时间
        String paymentTime = (String) map.get("paymentTime");
        // 第三方交易流水号
        String paymentOtherNumber = (String) map.get("paymentOtherNumber");
        String orderFrom = (String) map.get("orderFrom");
        // 支付订单信息
        List<String> orderIdList = new ArrayList<>();
        Map<String, Object> mapDigital = new HashMap<>();
        mapDigital.put("orderStatus", orderStatus);
        mapDigital.put("paymentId", paymentId);
        mapDigital.put("paymentName", paymentName);
        mapDigital.put("paymentTime", paymentTime);
        mapDigital.put("paymentOtherNumber", paymentOtherNumber);
        mapDigital.put("paymentNumber", paymentNumber);
        mapDigital.put("payCode", payCode);
        //参数不定
        mapDigital.put("orderFrom", orderFrom);
        if (MathUtil.isInteger(paymentNumber)) {
            // 是纯数字，则为实际支付单号
            boolean isBaseSuccess = false;
            if (orderFrom != null) {
                isBaseSuccess = this.baseMapper.updateBaseByPureDigital(mapDigital);
            } else {
                isBaseSuccess = this.baseMapper.fiveUpdateOrderBaseToPaymentByPureDigital(mapDigital);
            }
            boolean isGoodsSuccess = this.baseMapper.fiveUpdateOrderGoodsToGoodsStatusByPureDigital(orderStatus, paymentNumber);

            orderIdList.add(paymentNumber);
            flag = isBaseSuccess && isGoodsSuccess;
        } else {
            // 如果不是纯数字，则为支付单号
            boolean isBaseSuccess = false;
            boolean isGoodsSuccess = false;
            if (orderFrom != null) {
                isBaseSuccess = this.baseMapper.updateBaseToPayment(mapDigital);
            } else {
                isBaseSuccess = this.baseMapper.fiveUpdateOrderBaseToPayment(mapDigital);
            }
            orderIdList = this.baseMapper.queryOrderIdForPayNumber(paymentNumber);
            for (String orderNumber : orderIdList) {
                isGoodsSuccess = this.baseMapper.fiveUpdateOrderGoodsToGoodsStatus(orderStatus, orderNumber);
            }
            flag = isBaseSuccess && isGoodsSuccess;
        }
        //分佣订单更新
        Runnable fxThread = new FxThread(fxService, orderIdList);
        Thread thread = new Thread(fxThread);
        thread.start();
        return flag;
    }

    /**
     * 得到快递信息
     *
     * @param shippingCode
     * @param orderId
     * @param token
     * @return
     */
    public Map<String, String> getShipperCode2(String shippingCode, String orderId, String token) {
        Map map = new HashMap();
        Map result = orderGoodsMapper.getShipperCode2(shippingCode, orderId);
        //获取快递简称
        Integer orderShippingExpressId = (Integer) result.get("orderShippingExpressId");
        ResponseResult shipperResp = baseServiceClient.getBaseExpressInfoById(orderShippingExpressId);
        Map<String, String> shipperCode = JSONObject.parseObject(JSON.toJSONString(shipperResp.getData()), Map.class);
        map.put("shipperCode", shipperCode.get("expressPinyin"));
        map.put("expressName", shipperCode.get("expressName"));
        //获取快递鸟的配置
        ResponseResult expressResp = baseServiceClient.queryConfigFeign();
        BaseKdniaoConfigDTO expressQueryByKdNiao = JSON.parseObject(JSON.toJSONString(expressResp.getData()), BaseKdniaoConfigDTO.class);
        map.put("AppKey", expressQueryByKdNiao.getAppKey());
        map.put("EBussinessID", expressQueryByKdNiao.getEBussinessID());
        map.put("instructCode", expressQueryByKdNiao.getInstructCode());
        //获取收件人手机号的后4位
        String orderReceiverContact = (String) result.get("orderReceiverContact");
        String customerName = orderReceiverContact.substring(orderReceiverContact.length() - 4);
        map.put("customerName", customerName);
        return map;
    }

    public Boolean checkLimit(String limit, UserInfoVO platformUserInfo) {
        String limits = platformUserInfo.getRightsLimitsAll();

        // 判断是否是超级管理员
        if (platformUserInfo.getRightsGroupId() == 1) {
            return true;
        }
        // 判断是否为-1，如果！= -1 ，则有权限，返回true
        return (limits.indexOf(limit) != -1);
    }

    @Override
    public ResponseResult querySellerOrderInvoiceList(Map<String, Object> param) {
        ResponseResult rr = new ResponseResult();
        String token = (String) param.get("token");
        ObjectMapper mapper = new ObjectMapper();
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);

        Integer shopId = Integer.valueOf(ui.getShopId());
        if (null == shopId) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        ResponseResult result = checkToken(token);
        if (result.getCode() !=CommonStatusEnum.SUCCESS.getCode()) {
            return result;
        } else {
            param.put("userId", result.getData().toString());
        }
        try {
            IPage<SellerOrderInvoiceVO> page=this.baseMapper.querySellerOrderInvoiceInfo(new Query<SellerOrderInvoiceVO>().getPage(param),
                    param);
            for (SellerOrderInvoiceVO order : page.getRecords()) {
                param.put("orderId", order.getOrderId());
                List<OrderGoodsDetailVO> goodsInfo = orderBaseMapper.queryOrderGoodsInfo2(param);
                order.setGoodsList(goodsInfo);
                param.put("invoiceId", order.getInvoiceId());
                if (null != order.getInvoiceId()) {
                    Integer invoiceType = orderBaseMapper.getInvoiceType(param);
                    order.setInvoiceType(invoiceType);
                }
            }
            return ResponseResult.success(PageUtils.getPage(page));
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseResult.fail(e.getMessage());
        }
    }

    /**
     * 已售订单查询
     *
     * @param map
     * @return
     * @throws IOException
     * @throws JsonMappingException
     * @throws JsonParseException
     */
    @Override
    public ResponseResult soldOrders(Map<String, Object> map) {
        ResponseResult rr = new ResponseResult();
        String token = (String) map.get("token");
        boolean isExist = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (isExist) {
            try {
                UserInfoVO ui =ParseTokenUtils.getUserInfoByToken(token);
                Integer shopId = Integer.valueOf(ui.getShopId());
                if (null == ui.getShopId()) {
                    rr.setCode(CommonStatusEnum.FAIL.getCode());
                    rr.setMessage(BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
                    return rr;
                }
//                if (containLimits(ui, Seller_Trade_Order)) {
                String userName = (String) map.get("userName");
                String orderNum = (String) map.get("orderNum");
                String goodsName = (String) map.get("goodsName");
                String orderStartTime = (String) map.get("orderStartTime");
                String orderEndTime = (String) map.get("orderEndTime");
                Integer status = Integer.parseInt(map.get("status") + "");
                String allOrderStatus = null;
                Integer otherOrderStatus = null;
                //退货状态
                Integer orderReturnStatus1 = null;
                //退款状态
                Integer orderRefundStatus1 = null;
                if (status == 1) {
                    allOrderStatus = "' '";
                } else if (status == 2) {
                    // 待付款
                    otherOrderStatus = 1;
                    orderReturnStatus1 = 0;
                    orderRefundStatus1 = 0;
                } else if (status == 3) {
                    // 已付款
                    otherOrderStatus = 3;
                    orderReturnStatus1 = 0;
                    orderRefundStatus1 = 0;
                } else if (status == 4) {
                    // 已发货
                    otherOrderStatus = 4;
                    orderReturnStatus1 = 0;
                    orderRefundStatus1 = 0;
                } else if (status == 5) {
                    // 已完成
                    otherOrderStatus = 6;
                    orderReturnStatus1 = 0;
                    orderRefundStatus1 = 0;
                } else if (status == 6) {
                    // 已取消
                    otherOrderStatus = 7;
                    orderReturnStatus1 = 0;
                    orderRefundStatus1 = 0;
                } else if (status == 7) {
                    // 退货中
                    otherOrderStatus = null;
                    orderReturnStatus1 = 1;
                } else if (status == 8) {
                    // 退款中
                    otherOrderStatus = null;
                    orderRefundStatus1 = 1;
                } else if (status == 9) {
                    // 退款完成
                    otherOrderStatus = null;
                    orderRefundStatus1 = 2;
                } else if (status == 10) {
                    // 退货完成
                    otherOrderStatus = null;
                    orderReturnStatus1 = 2;
                }
                Integer dropShipping = null;
                if (null != map.get("dropShipping")) {
                    dropShipping = Integer.parseInt(map.get("dropShipping") + "");
                }

                map.put("shopId",shopId);
                map.put("allOrderStatus",allOrderStatus);
                map.put("otherOrderStatus",otherOrderStatus);
                map.put("orderReturnStatus",orderReturnStatus1);
                map.put("orderRefundStatus",orderRefundStatus1);
                map.put("userName",userName);
                map.put("orderNum",orderNum);
                map.put("goodsName",goodsName);
                map.put("orderStartTime",orderStartTime);
                map.put("orderEndTime",orderEndTime);
                map.put("orderType", CommonType.orderType.GOODS_TYPE.getCode());
                map.put("dropShipping",dropShipping);
                map.put("orderSource",2);

                IPage<OrderDetailsVO> page=this.baseMapper.queryOrderBase(new Query<OrderDetailsVO>().getPage(map),
                        map);


                for (int i = 0; i < page.getRecords().size(); i++) {
                    String orderId = page.getRecords().get(i).getOrderId();
                    // 退款状态
                    Integer orderRefundStatus =  page.getRecords().get(i).getOrderRefundStatus();
                    // 退货状态
                    Integer orderReturnStatus =  page.getRecords().get(i).getOrderReturnStatus();
                    // 订单状态
                    Integer normalStatus =  page.getRecords().get(i).getOrderStatus();
                    // 涉及退款退货订单状态
                    Integer Orderstatus = null;
                    //满减赠赠品信息
                    String giveawayInfo =  page.getRecords().get(i).getGiveawayInfo();

                    List<ManJianZengPinVO> list;
                    if (null != giveawayInfo && !"".equals(giveawayInfo)) {
                        list = JsonUtils.string2Obj(giveawayInfo, List.class, ManJianZengPinVO.class);
                        page.getRecords().get(i).setZengpinInfo(list);
                    }

                    if (normalStatus == 3) {
                        // 未发货状态
                        if (orderRefundStatus == 1) {
                            // 未发货退款中
                            Orderstatus = 22;
                        } else if (orderRefundStatus == 2) {
                            // 商家拒绝或审核通过，继续发货，但不可再次申请退款
                            Orderstatus = 26;
                        } else if (orderRefundStatus == 0) {
                            Orderstatus = 3;
                        }
                    } else if (normalStatus == 6) {
                        // 已完成状态
                        if (orderRefundStatus == 1) {
                            // 收货退款中
                            Orderstatus = 23;
                        } else if (orderRefundStatus == 2) {
                            Orderstatus = 25;
                        } else if (orderRefundStatus == 0 && orderReturnStatus == 0) {
                            Orderstatus = 6;
                        } else if (orderReturnStatus == 1) {
                            // 收货退货中
                            Orderstatus = 24;
                        } else if (orderReturnStatus == 2) {
                            Orderstatus = 25;
                        } else if (orderReturnStatus == 0 && orderRefundStatus == 0) {
                            Orderstatus = 6;
                        }
                    } else {
                        Orderstatus = normalStatus;
                    }
                    // 存放最新状态
                    page.getRecords().get(i).setOrderStatus(Orderstatus);
                    List<GoodsDetailsVO> queryOrderDetails = orderBaseMapper.queryOrders(orderId);
                    if (queryOrderDetails != null) {
                        page.getRecords().get(i).setGoodsDetails(queryOrderDetails);
                    } else {
                        rr.setCode(CommonStatusEnum.FAIL.getCode());
                        rr.setMessage(BizCodeEnume.ORDER_IS_NULL.getMsg());
                    }
                }

                return ResponseResult.success(PageUtils.getPage(page));
            } catch (Exception e) {
                rr.setCode(500);
                log.info("SoldOrdersErrorResults:" + e.getMessage());
            }
        } else {
            rr.setCode(CommonStatusEnum.FAIL.getCode());
            rr.setMessage(BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        return rr;
    }

    /**
     * 伪删除
     *
     * @param map
     * @return
     */
    @Override
    @Transactional
    public ResponseResult pseudoDelete(Map<String, Object> map) {
        ResponseResult rr = new ResponseResult();
        String token = (String) map.get("token");
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
        if (ui!=null) {
            Integer shopId = Integer.valueOf(ui.getShopId());
            if (null == shopId) {
                return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(), BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
            }
            String orderId = (String) map.get("orderId");
            boolean isSuccess = orderBaseMapper.pseudoDelete(orderId);
            if (isSuccess) {
                return ResponseResult.success(BizCodeEnume.DELETE_SUCCESS);
            } else {
                return ResponseResult.fail(BizCodeEnume.DELETE_ERROR);
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }

    }

    @Override
    public ResponseResult dailyTurnoverOfThePlatform(Map<String, Object> map) {
        String token = (String) map.get("token");
        UserInfoVO info = ParseTokenUtils.getUserInfoByToken(token);
        if (info != null) {
            try {
                BigDecimal sales = new BigDecimal(0);
                sales = orderBaseMapper.queryTodaySales();
                sales = sales.setScale(2, BigDecimal.ROUND_HALF_UP);
                return ResponseResult.success(sales);
            } catch (Exception e) {
                return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(), BizCodeEnume.SYSTEM_ERROR.getMsg());
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(), BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
    }

    /**
     * 订单详情
     *
     * @param map
     * @return
     */
    @Override
    @SuppressWarnings("unused")
    public ResponseResult businessManageByOrderDetails(Map<String, Object> map) {
        ResponseResult rr = new ResponseResult();
        String token = (String) map.get("token");
        boolean isExist = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (isExist) {
            ResponseResult res = ParseTokenUtils.getShopUserInfo(token);
            if (res.getCode() != CommonStatusEnum.SUCCESS.getCode()) {
                return res;
            }
            String orderNum = (String) map.get("orderNum");
            MerchantsOrdersDetailsVO mod = orderBaseMapper.queryByOrderDetails(orderNum);
            if(mod.getOrderShippingExpressId() != null && mod.getOrderShippingExpressId() != 0){
                mod.setOrderShippingExpress(baseServiceClient.queryBaseExpressById(mod.getOrderShippingExpressId()));
            }
            // 退货状态
            Integer orderReturnStatus = mod.getOrderReturnStatus();
            // 订单状态
            Integer normalStatus = mod.getOrderStatus();
            //满减赠赠品信息
            String giveawayInfo = mod.getGiveawayInfo();
            //支付方式
            Integer paymentCode = mod.getPaymentCode();
            if (paymentCode != null){
                if (paymentCode == 1){
                    mod.setPaymentName("线上支付");
                }else if (paymentCode == 2){
                    mod.setPaymentName("线下支付");
                }else if (paymentCode == 3){
                    mod.setPaymentName("货到付款");
                }
            }
            List<ManJianZengPinVO> list;
            if (null != giveawayInfo && !giveawayInfo.isEmpty()) {
                list = JsonUtils.string2Obj(giveawayInfo, List.class, ManJianZengPinVO.class);
                mod.setZengpinInfo(list);
            }
            // 涉及退款退货订单状态
            Integer Orderstatus = null;
            Integer orderRefundStatus = null;
            // 退款状态
            orderRefundStatus = mod.getOrderRefundStatus();
            if (normalStatus == 3) {
                // 未发货状态
                if (orderRefundStatus != null && orderRefundStatus == 1) {
                    // 未发货退款中
                    Orderstatus = 22;
                } else if (orderRefundStatus != null && orderRefundStatus == 2) {
                    // 商家拒绝或审核通过，继续发货，但不可再次申请退款
                    Orderstatus = 26;
                } else if (orderRefundStatus != null && orderRefundStatus == 0) {
                    Orderstatus = 3;
                }
            } else if (normalStatus == 6) {
                // 已完成状态
                if (orderRefundStatus != null && orderRefundStatus == 1) {
                    // 收货退款中
                    Orderstatus = 23;
                } else if (orderRefundStatus != null && orderRefundStatus == 2) {
                    Orderstatus = 25;
                } else if (orderReturnStatus == 0 && orderReturnStatus == 0) {
                    Orderstatus = 6;
                } else if (orderReturnStatus != null && orderReturnStatus == 1) {
                    // 收货退货中
                    Orderstatus = 24;
                } else if (orderReturnStatus != null && orderReturnStatus == 2) {
                    Orderstatus = 25;
                } else if (orderRefundStatus != null && orderReturnStatus == 0 && orderRefundStatus == 0) {
                    Orderstatus = 6;
                }
            } else {
                Orderstatus = normalStatus;
            }
            // 存放最新状态
            mod.setOrderStatus(Orderstatus);
            List<AddOrderDetailsVO> aod = orderBaseMapper.queryNewOrderDetails(orderNum);
            //查询商品分类的抽佣比例
            if (null != aod && !aod.isEmpty()) {
                for (AddOrderDetailsVO addOrderDetails : aod) {
                    BigDecimal bili = orderBaseMapper.queryCatChouYong(addOrderDetails.getGoodsId());
                    addOrderDetails.setChouYongBili(null == bili ? new BigDecimal(0) : bili);
                }
            }
            // 发票状态
            mod.setInvoiceState(StrUtil.isEmptyIfStr(mod.getOrderInvoiceId()) ? 1 : 4);
            List<ReturnOrderDetailsVO> rod = orderBaseMapper.queryReturnOrderDetails(orderNum);
            mod.setAddOrderDetails(aod);
            mod.setReturnOrderDetails(rod);
            return ResponseResult.success(mod);
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }

    }

    @Override
    public ResponseResult getRedPacketOrder(Map<String, String> paraMap) {
        List<OrderBaseEntity> list = this.baseMapper.selectList(new LambdaQueryWrapper<OrderBaseEntity>()
                .eq(OrderBaseEntity::getRedpacketCode, paraMap.get("redpacketId").toString()));
        return ResponseResult.success(list);
    }

    @Override
    public ResponseResult queryPlatFormMemberSelfPard(PlatFormMemberSelfQueryDTO param) throws IllegalAccessException {
        Map<String, Object> result = new HashMap<>();
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        if (checkLimit("orderList", userInfo)) {
            if (param.getOrderStatus().equals("1")) {
                // 全部订单
                param.setOrderStatus("");
            } else if (param.getOrderStatus().equals("2")) {
                // 待付款订单
                param.setOrderStatus("1");
            } else if (param.getOrderStatus().equals("3")) {
                // 已付款待发货订单
                param.setOrderStatus("3");
            } else if (param.getOrderStatus().equals("4")) {
                // 已发货订单
                param.setOrderStatus("4");
            } else if (param.getOrderStatus().equals("5")) {
                // 已完成订单
                param.setOrderStatus("6");
            } else if (param.getOrderStatus().equals("6")) {
                // 已取消订单
                param.setOrderStatus("7");
            } else if (param.getOrderStatus().equals("7")) {
                param.setOrderStatus("0");
            }
            if (userInfo.getRightsGroupId() == 2) {

                String districtIds = this.baseMapper.queryAerasBySub(userInfo.getSubSiteId());
                param.setDistrictCityId(districtIds);
                int a = 0;
                String isNotshopId = "";
                List<String> shopIdNo = this.baseMapper.queryfranchisesType();
                // 查询odb_shop_franchises_type，避免一些店铺
                if (!(shopIdNo.size() == 0)) {
                    for (String shopid : shopIdNo) {
                        if (a == 0) {
                            isNotshopId += shopid;
                        } else {
                            isNotshopId += "," + shopid;
                        }
                        a++;
                    }
                }
                List<String> shopIds = this.baseMapper.queryShopBudistrictAndshopIdNo(districtIds,
                        isNotshopId);
                String parentShopid = "";
                String parentUsers = "";
                int i = 0;
                if (!(shopIds.size() == 0)) {
                    for (String shopid : shopIds) {
                        if (i == 0) {
                            parentShopid += shopid;
                        } else {
                            parentShopid += "," + shopid;
                        }
                        i++;
                    }
                    int b = 0;
                    List<String> users = this.baseMapper.queryUserByparentShopId(parentShopid);
                    if (!(users.size() == 0)) {
                        for (String user : users) {
                            if (b == 0) {
                                parentUsers += user;
                            } else {
                                parentUsers += "," + user;
                            }
                            b++;
                        }
                    } else {
                        parentUsers = "-1";
                    } // 当users为空时，设置users="-1",避免查询全部订单

                } else {
                    parentUsers = "-1";

                } // 当shopid为空时，设置users="-1",避免查询全部订单

                param.setBuyerUserId(parentUsers);
            } else {
                if (param.getOrderId() == "") {
                    if (param.getAirTime() == "" && param.getFinishTime() == "" && param.getBuyerUserName() == "") {
                        System.out.println(1);
                        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String finishTime = dateformat.format(new Date());
                        Calendar c = Calendar.getInstance();
                        // 过去三个月
                        c.setTime(new Date());
                        c.add(Calendar.MONTH, -1);
                        Date m3 = c.getTime();
                        String startTime = dateformat.format(m3);
                        param.setAirTime(startTime);
                        param.setFinishTime(finishTime);

                    }

                }
            }
            Map data = ParseMapUtils.beanToMap(param);
            IPage<PlatFormMemberSelfQueryVO> page = this.baseMapper.queryPlatFormMemberSelfPard(new Query<PlatFormMemberSelfQueryVO>().getPage(data),
                    param);
            String totMoney = this.baseMapper.queryMemberSelfMoney(param);
            if (totMoney == null) {
                totMoney = "0";
            }
            result.put("totalAmount", totMoney);
            for (PlatFormMemberSelfQueryVO he : page.getRecords()) {
                if (he.getOrderRefundStatus() != null || he.getOrderReturnStatus() != null) {
                    if ((he.getOrderRefundStatus() + "状态").equals("0状态")
                            && (he.getOrderReturnStatus() + "状态").equals("0状态")) {
                        // 1无退款退货
                        he.setIsNotreFundReturn("1");

                    } else {
                        // 2有退款退货
                        he.setIsNotreFundReturn("2");
                    }
                } else {
                    // 1无退款退货
                    he.setIsNotreFundReturn("1");

                }
            }
            result.put("page", PageUtils.getPage(page));
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        return ResponseResult.success(result);
    }

    @Override
    public ResponseResult shipments(Map<Object, Object> map) throws TransactionException {
        String token = map.get("token").toString();
        UserInfoVO rr = ParseTokenUtils.getPlatformUser(token);
        if (rr == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        String orderShippingCode = map.get("orderShippingCode").toString();
        if ("".equals(orderShippingCode.trim())) {
            return ResponseResult.fail(BizCodeEnume.SHOPPING_CODE_IS_NULL);
        }
        return piLiangFahuoShipments(map, CommonType.commonStatus.NO.getCode());
    }

    @Override
    public ResponseResult deleteIntegralOrder(Map<Object, Object> map) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(map.get("token").toString());
        if (null != userInfo) {
            this.baseMapper.delete(new LambdaQueryWrapper<OrderBaseEntity>()
                    .eq(OrderBaseEntity::getOrderId, map.get("orderId").toString())
                    .eq(OrderBaseEntity::getIntegralGoods, CommonType.commonStatus.NO.getCode()));
            return ResponseResult.success();
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult queryMonthsaleReport(MonthReportDTO param) {
        if (null == param) {
            param = new MonthReportDTO();
        }
        if (param.getOrderId() == "") {
            if (param.getPaymentTimeStart() == "" && param.getPaymentTimeEnd() == "") {
                SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String finishTime = dateformat.format(new Date());
                Calendar c = Calendar.getInstance();
                // 过去三个月
                c.setTime(new Date());
                c.add(Calendar.MONTH, -1);
                Date m3 = c.getTime();
                String startTime = dateformat.format(m3);

                param.setOrderCreateTimeEnd(finishTime);
                param.setOrderCreateTimeStart(startTime);
            }

        }
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        if (null != userInfo) {
            try {
                //将对象转换为map
                Map data = ParseMapUtils.beanToMap(param);
                //分页查询数据
                IPage<MonthReportSalesVO> page = this.baseMapper.queryMonthsaleReport(new Query<MonthReportSalesVO>().getPage(data), param);
                List<MonthReportSalesVO> records = page.getRecords();
                Integer returnFlag = 0;
                for (MonthReportSalesVO record : records) {
                    OrderBaseEntity orderInfoEntity = this.baseMapper.selectById(record.getOrderId());
                    Integer virtualGoods = orderInfoEntity.getVirtualGoods();
                    Integer orderIsShopTake = orderInfoEntity.getOrderIsShopTake();
                    if (null != orderIsShopTake && 1 == orderIsShopTake) {
                        record.setOrderType(3);
                    } else {
                        if (null != virtualGoods && 0 == virtualGoods) {
                            record.setOrderType(2);
                            record.setPastDue(orderInfoEntity.getPastDue());
                            record.setIsCancel(orderInfoEntity.getIsCancel());
                        } else {
                            record.setOrderType(1);
                        }
                    }
                    String returnStatus = orderInfoEntity.getOrderReturnStatus();
                    String refundStatus = orderInfoEntity.getOrderRefundStatus();
                    record.setReturnStatus(returnStatus);
                    record.setRefundStatus(refundStatus);
                    if (returnStatus.equals("2") || refundStatus.equals("2")) {
                        BigDecimal returnAmount = BigDecimal.valueOf(orderInfoEntity.getOrderRefundAmount());
                        BigDecimal orderAmount = orderInfoEntity.getOrderPaymentAmount();
                        if (orderAmount.compareTo(returnAmount) > 0) {
                            returnFlag = 2;
                        } else if ((orderAmount.compareTo(returnAmount) == 0)) {
                            returnFlag = 1;
                        }
                    }
                    record.setReturnFlag(returnFlag);
                    List<GoodsDetailsVO> parm = this.baseMapper.queryGoodsDetail(record.getOrderId());
                    record.setGoods(parm);
                    if (null != record.getPayCode() && "6".equals(record.getPayCode())) {
                        //购物卡支付
                        record.setTradePaymentRechargeCard(record.getOrderPaymentAmount());
                    } else if ((null != record.getPayCode())
                            && ("3".equals(record.getPayCode()) || "2".equals(record.getPayCode()))) {
                        //第三方支付
                        record.setTradeThirdPartyAmount(record.getOrderPaymentAmount());
                    }
                }
                return ResponseResult.success(PageUtils.getPage(page));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult queryMonthsaleReportExcel(MonthReportDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (null != userInfo) {
            List<MonthReportSalesVO> page = this.baseMapper.queryMonthsaleReportExcel(param);
            String[] title = {"订单号", "支付时间", "卖家店铺名称", "运费", "红包面额", "应付金额", "订单状态", "支付方式", "买家名称", "订单完成时间", "支付单号",
                    "第三方支付平台交易号", "订单物流", "商品物流", "订单来源", "商品名", "商品价格", "商品数量", "退货数量", "渠道号", "充值卡余额支付", "第三方支付金额"};

            List<Map<String, String>> list = Lists.newArrayList();

            for (MonthReportSalesVO res : page) {
                HashMap<String, String> map = com.google.common.collect.Maps.newHashMap();
                // 订单状态 1.待付款 2.已付款 3.待发货 4.已发货 5.已签收 6.确认收货 7.取消 8.退款中 9.已退款 11.待自提',
                if (res.getOrderStatus() != null) {

                    switch (res.getOrderStatus()) {
                        case "1":
                            res.setOrderStatus("待付款 ");
                            break;
                        case "2":
                            res.setOrderStatus("已付款");
                            break;
                        case "3":
                            res.setOrderStatus("待发货  ");
                            break;
                        case "4":
                            res.setOrderStatus("已发货 ");
                            break;
                        case "5":
                            res.setOrderStatus("已签收 ");
                            break;
                        case "6":
                            res.setOrderStatus("确认收货");
                            break;
                        case "7":
                            res.setOrderStatus("取消 ");
                            break;
                        case "8":
                            res.setOrderStatus("退款中");
                            break;
                        case "9":
                            res.setOrderStatus("已退款 ");
                            break;
                        case "11":
                            res.setOrderStatus("待自提");
                            break;
                        case "12":
                            res.setOrderStatus("已过期");
                            break;
                    }
                }
                if (res.getPayCode() != null) {

                    switch (res.getPayCode()) {
                        // 1-余额支付，2-支付宝支付，3-微信支付，5-健康账户余额支付',
                        case "1":
                            res.setPayCode("余额支付");
                            break;
                        case "2":
                            res.setPayCode("支付宝支付");
                            break;
                        case "3":
                            res.setPayCode("微信支付");
                            break;
                        case "6":
                            res.setPayCode("充值卡余额支付 ");
                            break;
                    }
                }

                if (res.getOrderFrom() != null) {

                    switch (res.getOrderFrom()) {
                        case "1":
                            res.setOrderFrom("pc");
                            break;
                        case "2":
                            res.setOrderFrom("wap");
                            break;
                        case "3":
                            res.setOrderFrom("安卓");
                            break;
                        case "5":
                            res.setOrderFrom("iOS");
                            break;
                        case "6":
                            res.setOrderFrom("小程序");
                            break;
                    }

                }
                map.put("订单号", res.getOrderId() + "");
                map.put("支付时间", res.getPaymentTime() == null ? "": format.format(res.getPaymentTime()));
                map.put("卖家店铺名称", res.getShopName() + "");
                map.put("运费", res.getOrderShippingFee() + "");
                map.put("红包面额", res.getRedpacketPrice() + "");
                map.put("应付金额", res.getOrderPaymentAmount() + "");
                map.put("订单状态", res.getOrderStatus() + "");
                map.put("支付方式", res.getPayCode() + "");
                map.put("买家名称", res.getBuyerUserName() + "");
                map.put("订单完成时间", res.getOrderFinishedTime() == null ? "": format.format(res.getOrderFinishedTime()));
                map.put("支付单号", res.getPaymentNumber() + "");
                map.put("第三方支付平台交易号", res.getPaymentOtherNumber() == null ? "": String.valueOf(res.getPaymentOtherNumber()));
                map.put("订单物流", res.getOrderShippingCode() == null ? "": String.valueOf(res.getOrderShippingCode()));
                map.put("订单来源", res.getOrderFrom() + "");
                map.put("商品名", res.getGoodsName()  == null ? "": String.valueOf(res.getGoodsName()));
                map.put("商品价格", res.getGoodsPrice()  == null ? "": String.valueOf(res.getGoodsPrice()));
                map.put("商品数量", res.getOrderGoodsNum()  == null ? "": String.valueOf(res.getOrderGoodsNum()));
                map.put("退货数量", res.getOrderGoodsReturnnum()  == null ? "": String.valueOf(res.getOrderGoodsReturnnum()));
                map.put("充值卡余额支付", res.getTradePaymentRechargeCard() + "");
                map.put("第三方支付金额", res.getTradeThirdPartyAmount() + "");
                list.add(map);
            }
            // excel文件名
            Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
             * 该list为每个sheet页的数据
             */> map = Maps
                    .newHashMap();
            map.put("交易明细", list);
            String url = ExcelsUtil.createExcel(title, map,
                    new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);

            return ResponseResult.success(url);
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult queryRealOrderSelfPardExcel(RealOrderSelfDTO param) {
        if (null == param) {
            param = new RealOrderSelfDTO();
        }
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());

        if (null == userInfo || userInfo.equals("")) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String finishTime = dateformat.format(new Date());
        if (param.getOrderId() == "") {
            if (param.getAirTime() == "" && param.getFinishTime() == "" && param.getBuyerUserName() == "") {
                Calendar c = Calendar.getInstance();
                // 过去三个月
                c.setTime(new Date());
                c.add(Calendar.MONTH, -3);
                Date m3 = c.getTime();
                String startTime = dateformat.format(m3);
                param.setStartTime(startTime);
                param.setEndTime(finishTime);

            }
        }
        if (param.getOrderStatus().equals("1")) {
            // 全部订单
            param.setOrderStatus("");
        } else if (param.getOrderStatus().equals("2")) {
            // 待付款订单
            param.setOrderStatus("1");
        } else if (param.getOrderStatus().equals("3")) {
            // 已付款待发货订单
            param.setOrderStatus("3");
            param.setOrderReturnStatus("0");
            param.setOrderRefundStatus("0");
        } else if (param.getOrderStatus().equals("4")) {
            // 已发货订单
            param.setOrderStatus("4");
            param.setOrderReturnStatus("0");
            param.setOrderRefundStatus("0");
        } else if (param.getOrderStatus().equals("5")) {
            // 已完成订单
            param.setOrderStatus("6");
            param.setOrderReturnStatus("0");
            param.setOrderRefundStatus("0");
        } else if (param.getOrderStatus().equals("6")) {
            // 已取消订单
            param.setOrderStatus("7");
        } else if (param.getOrderStatus().equals("7")) {
            param.setOrderStatus("");
            param.setOrderReturnStatus("1");
        }else if (param.getOrderStatus().equals("8")) {
            param.setOrderStatus("");
            param.setOrderRefundStatus("1");
        }else if (param.getOrderStatus().equals("9")) {
            param.setOrderStatus("");
            param.setOrderRefundStatus("2");
        }else if (param.getOrderStatus().equals("10")) {
            param.setOrderStatus("");
            param.setOrderReturnStatus("2");
        }
        int a = 0;
        String isNotshopId = "";
        List<String> shopIdNo = this.baseMapper.queryfranchisesType();
        // 查询odb_shop_franchises_type，避免一些店铺
        if (!(shopIdNo.isEmpty())) {
            for (String shopid : shopIdNo) {
                if (a == 0) {
                    isNotshopId += shopid;
                } else {
                    isNotshopId += "," + shopid;
                }
                a++;
            }
        }
        param.setShopIdReal(isNotshopId);
        List<PlatFormMemberSelfQueryVO> page = this.baseMapper.queryRealOrderSelfPardExccel(param);
        if (page.size() > 30000) {
            //导出数量过大，请联系运维
            return ResponseResult.fail(BizCodeEnume.EXPORT_QUANTITY_IS_TOO_LARGE);
        }
        String[] headers = {"订单编号", "订单来源", "收货人名称", "下单时间", "商品金额", "支付金额",
                "代金券", "运费", "订单状态", "活动ID", "退款状态", "退货状态",
                "是否存在退货退款", "支付单号", "支付方式名称", "支付时间", "发货物流单号", "退款金额", "订单完成时间",
                "是否评价", "店铺id", "店铺名", "买家id", "买家名", "充值卡余额支付", "第三方支付金额", "支付方式"};
        List<Map<String, String>> list = Lists.newArrayList();
        for (PlatFormMemberSelfQueryVO res : page) {
            HashMap<String, String> map = Maps.newHashMap();
            if (res.getOrderStatus() != null) {
                switch (res.getOrderStatus()) {
                    case "1":
                        res.setOrderStatus("待付款 ");
                        break;
                    case "2":
                        res.setOrderStatus("已付款");
                        break;
                    case "3":
                        res.setOrderStatus("待发货  ");
                        break;
                    case "4":
                        res.setOrderStatus("已发货 ");
                        break;
                    case "5":
                        res.setOrderStatus("已签收 ");
                        break;
                    case "6":
                        res.setOrderStatus("确认收货");
                        break;
                    case "7":
                        res.setOrderStatus("取消 ");
                        break;
                    case "8":
                        res.setOrderStatus("退款中");
                        break;
                    case "9":
                        res.setOrderStatus("已退款 ");
                        break;
                    case "11":
                        res.setOrderStatus("待自提");
                        break;

                }
            }
            if (res.getOrderFrom() != null) {

                switch (res.getOrderFrom()) {
                    //1PC 2wap微信浏览器 3安卓 5ios 6微信小程序 7wap浏览器
                    case "1":
                        res.setOrderFrom("pc");
                        break;
                    case "2":
                        res.setOrderFrom("wap微信浏览器");
                        break;
                    case "3":
                        res.setOrderFrom("安卓");
                        break;
                    case "5":
                        res.setOrderFrom("ios");
                        break;
                    case "6":
                        res.setOrderFrom("微信小程序");
                        break;
                    case "7":
                        res.setOrderFrom("wap浏览器");
                        break;
                }
            }
            if (null != res.getOrderReturnStatus() && res.getOrderRefundStatus() != null) {
                if ("0".equals(res.getOrderReturnStatus()) && "0".equals(res.getOrderRefundStatus())) {
                    res.setIsNotreFundReturn("否");
                } else {
                    res.setIsNotreFundReturn("是");
                }
            } else {
                res.setIsNotreFundReturn("否");
            }
            if (res.getOrderRefundStatus() != null) {

                switch (res.getOrderRefundStatus()) {
                    // 0是无退款,1是退款中,2是退款完成',
                    case "0":
                        res.setOrderRefundStatus("无退款");
                        break;
                    case "1":
                        res.setOrderRefundStatus("退款中 ");
                        res.setOrderStatus("退款中 ");
                        break;
                    case "2":
                        res.setOrderRefundStatus("退款完成");
                        res.setOrderStatus("退款完成 ");
                        break;

                }
            }
            if (res.getOrderReturnStatus() != null) {
                switch (res.getOrderReturnStatus()) {
                    // 0是无退款,1是退款中,2是退款完成',
                    case "0":
                        res.setOrderReturnStatus("无退货");
                        break;
                    case "1":
                        res.setOrderReturnStatus("退货中 ");
                        res.setOrderStatus("退货中 ");
                        break;
                    case "2":
                        res.setOrderReturnStatus("退货完成");
                        res.setOrderStatus("退货完成 ");
                        break;

                }
            }

            if (res.getPayCode() != null) {

                switch (res.getPayCode()) {
                    // 1-余额支付，2-支付宝支付，3-微信支付，',
                    case "1":
                        res.setPayCode("余额支付");
                        break;
                    case "2":
                        res.setPayCode("支付宝支付");
                        break;
                    case "3":
                        res.setPayCode("微信支付");
                        break;
                }
            }
            if (res.getOrderBuyerEvaluationStatus() != null) {
                switch (res.getOrderBuyerEvaluationStatus()) {
                    case "0":
                        res.setOrderBuyerEvaluationStatus("未评价");
                        break;
                    case "1":
                        res.setOrderBuyerEvaluationStatus("已评价 ");
                        break;

                }
            }
            map.put("订单编号", res.getOrderId());
            map.put("订单来源", res.getOrderFrom());
            map.put("收货人名称", res.getOrderReceiverName());
            map.put("下单时间", res.getOrderCreateTime().toString());
            map.put("商品金额", res.getOrderGoodsAmount().toString());
            map.put("支付金额", res.getOrderPaymentAmount().toString());
            map.put("代金券", res.getVoucherPrice().toString());
            map.put("运费", res.getOrderShippingFee().toString());
            map.put("订单状态", res.getOrderStatus());
            map.put("活动ID", res.getOrderPromotionId().toString());
            map.put("退款状态", res.getOrderRefundStatus());
            map.put("退货状态", res.getOrderReturnStatus());
            map.put("是否存在退货退款", res.getIsNotreFundReturn());
            map.put("支付单号", res.getPaymentNumber());
            map.put("支付方式名称", res.getPaymentName());
            map.put("支付时间", res.getPaymentTime() != null ? res.getPaymentTime().toString() : "");
            map.put("发货物流单号", res.getOrderShippingCode());
            map.put("退款金额", res.getOrderRefundAmount() != null ? res.getOrderRefundAmount().toString() : "0");
            map.put("订单完成时间", res.getOrderFinishedTime() != null ? res.getOrderFinishedTime().toString() : "");
            map.put("是否评价", res.getOrderBuyerEvaluationStatus());
            map.put("店铺id", res.getShopId().toString());
            map.put("店铺名", res.getShopName());
            map.put("买家id", res.getBuyerUserId());
            map.put("买家名", res.getBuyerUserName());
            map.put("充值卡余额支付", res.getTradePaymentRechargeCard() != null ? res.getTradePaymentRechargeCard().toString() : "0");
            map.put("第三方支付金额", res.getTradeThirdPartyAmount() != null ? res.getTradeThirdPartyAmount().toString() : "0");
            map.put("支付方式", res.getPayCode());

            list.add(map);
        }

        // excel文件名
        Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
         * 该list为每个sheet页的数据
         */> map = Maps.newHashMap();
        map.put("测试合并数据", list);
        String url = ExcelsUtil.createExcel(headers, map, new int[]{0}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);
        return ResponseResult.success(url);
}

    @Override
    public ResponseResult queryRealOrderSelfPard(RealOrderSelfDTO param) throws IllegalAccessException {
        UserInfoVO userInfo=ParseTokenUtils.getPlatformUser(param.getToken());
        if(userInfo==null){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        if (LimitUtils.checkLimit("realOrder", userInfo)) {
            if (param.getOrderStatus().equals("1")) {
                // 全部订单
                param.setOrderStatus("");
            } else if (param.getOrderStatus().equals("2")) {
                // 待付款订单
                param.setOrderStatus("1");
            } else if (param.getOrderStatus().equals("3")) {
                // 已付款待发货订单
                param.setOrderStatus("3");
                param.setOrderReturnStatus("0");
                param.setOrderRefundStatus("0");
            } else if (param.getOrderStatus().equals("4")) {
                // 已发货订单
                param.setOrderStatus("4");
                param.setOrderReturnStatus("0");
                param.setOrderRefundStatus("0");
            } else if (param.getOrderStatus().equals("5")) {
                // 已完成订单
                param.setOrderStatus("6");
                param.setOrderReturnStatus("0");
                param.setOrderRefundStatus("0");
            } else if (param.getOrderStatus().equals("6")) {
                // 已取消订单
                param.setOrderStatus("7");
            } else if (param.getOrderStatus().equals("7")) {
                param.setOrderStatus("");
                param.setOrderReturnStatus("1");
            }else if (param.getOrderStatus().equals("8")) {
                param.setOrderStatus("");
                param.setOrderRefundStatus("1");
            }else if (param.getOrderStatus().equals("9")) {
                param.setOrderStatus("");
                param.setOrderRefundStatus("2");
            }else if (param.getOrderStatus().equals("10")) {
                param.setOrderStatus("");
                param.setOrderReturnStatus("2");
            }
            if (userInfo.getRightsGroupId() != 2) {

                int a = 0;
                String isNotshopId = "";
                List<String> shopIdNo = this.baseMapper.queryfranchisesType();
                // 查询odb_shop_franchises_type，避免一些店铺
                if (!(shopIdNo.size() == 0)) {
                    for (String shopid : shopIdNo) {
                        if (a == 0) {
                            isNotshopId += shopid;
                        } else {
                            isNotshopId += "," + shopid;
                        }
                        a++;
                    }
                }
                Integer returnFlag = 0;
                param.setShopIdReal(isNotshopId);
                Map data= ParseMapUtils.beanToMap(param);
                IPage<PlatFormMemberSelfQueryVO> page = this.baseMapper.queryRealOrderSelfPard(new Query<PlatFormMemberSelfQueryVO>().getPage(data), param);

                for(PlatFormMemberSelfQueryVO r:page.getRecords()){
                    OrderBaseEntity orderInfoEntity =this.baseMapper.selectById(r.getOrderId());
                    Integer virtualGoods = orderInfoEntity.getVirtualGoods();
                    Integer orderIsShopTake = orderInfoEntity.getOrderIsShopTake();
                    if( null != orderIsShopTake && 1 == orderIsShopTake){
                        r.setOrderType(3);
                    }else{
                        if(null != virtualGoods && 0 == virtualGoods){
                            r.setOrderType(2);
                            r.setPastDue(orderInfoEntity.getPastDue());
                            r.setIsCancel(orderInfoEntity.getIsCancel());
                        }else{
                            r.setOrderType(1);
                        }
                    }
                    String returnStatus = orderInfoEntity.getOrderReturnStatus();
                    String refundStatus = orderInfoEntity.getOrderRefundStatus();
                    r.setReturnStatus(Integer.valueOf(returnStatus));
                    r.setRefundStatus(Integer.valueOf(refundStatus));
                    if (returnStatus.equals("2") || refundStatus.equals("2")) {
                        BigDecimal returnAmount = new BigDecimal(orderInfoEntity.getOrderRefundAmount());
                        BigDecimal orderAmount = orderInfoEntity.getOrderPaymentAmount();
                        if (orderAmount.compareTo(returnAmount) > 0) {
                            returnFlag = 2;
                        } else if ((orderAmount.compareTo(returnAmount) == 0)) {
                            returnFlag = 1;
                        }
                    }
                    r.setReturnFlag(returnFlag);
                    if(null != r.getPayCode() && "1".equals(r.getPayCode())){
                        //余额支付
                        r.setTradePaymentMoney(r.getOrderPaymentAmount());
                    }else if(null != r.getPayCode() && "6".equals(r.getPayCode())  ){
                        //购物卡支付
                        r.setTradePaymentRechargeCard(r.getOrderPaymentAmount());
                    }else if((null != r.getPayCode()) && ("3".equals(r.getPayCode())  || "2".equals( r.getPayCode()))){
                        //第三方支付
                        r.setTradeThirdPartyAmount(r.getOrderPaymentAmount());
                    }
                    r.setOrderAmountNoShippingFee(new BigDecimal(r.getOrderPaymentAmount()).subtract(new BigDecimal(r.getOrderShippingFee())).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
              return ResponseResult.success(PageUtils.getPage(page));
            } else {
                return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateByMap(Map<String, Object> map) {
        Integer count = this.baseMapper.updateOrderBaseByMap(map);
        if (count > 0) {
            return ResponseResult.success(BizCodeEnume.UPDATE_SUCCEEDED);
        }
        return ResponseResult.fail(BizCodeEnume.UPDATE_ERROR);
    }

    @Override
    public ResponseResult queryReturnBondDetail(Map<String, Object> map) {
        Integer shopId = Integer.valueOf(map.get("shopId").toString());
        // 未下架数量
        Integer onshelves = this.baseMapper.selectGoodsStatus(shopId);
        map.put("onshelves",onshelves);
        // 未发货/未结算
        map = this.baseMapper.setNoSendGoods(shopId);

        return ResponseResult.success(map);
    }

    @Override
    public ResponseResult updateShopByOrderInfo(Map<String, Object> map) {
        String shopId = map.get("shopId").toString();
        List<OrderBaseEntity> orderBaseEntityList = this.baseMapper.selectList(new LambdaQueryWrapper<OrderBaseEntity>()
                .eq(OrderBaseEntity::getShopId, shopId));

        Boolean status = false;
        if (CollectionUtils.isNotEmpty(orderBaseEntityList)) {
            for (OrderBaseEntity entity : orderBaseEntityList) {
                //订单未完成不能删除,否则可以删除
                Boolean flag = false;
                //非虚拟订单
                if (entity.getVirtualGoods().equals(CommonType.commonStatus.YES.getCode())) {
                    //订单待付款并且已取消
                    if (entity.getOrderStatus().equals(CommonType.orderStatus.TO_BE_PAID.getCode()) && entity.getOrderDel().equals(CommonType.commonStatus.YES.getCode())) {
                        flag = true;
                    }
                    //已付款并且退款完成
                    if (entity.getOrderStatus().equals(CommonType.orderStatus.PAID.getCode()) && (entity.getOrderRefundStatus().equals(CommonType.commonStatus.OTHER.getCode()))) {
                        flag = true;
                    }
                    //已付款并且退货完成
                    if (entity.getOrderStatus().equals(CommonType.orderStatus.PAID.getCode()) && (entity.getOrderReturnStatus().equals(CommonType.commonStatus.NO.getCode()))) {
                        flag = true;
                    }
                    //订单完成并且超过7天售后期
                    if (entity.getOrderStatus().equals(CommonType.orderStatus.CONFIRM_RECEIPT.getCode())
                            && (DateUtils.getBetweenDays(entity.getOrderFinishedTime(), new Date()) > 7)) {
                        flag = true;
                    }
                    if (!flag) {
                        break;
                    }
                } else {
                    //虚拟订单
                    //订单待付款并且已取消
                    if (entity.getOrderStatus().equals(CommonType.orderStatus.TO_BE_PAID.getCode()) && entity.getOrderDel().equals(CommonType.commonStatus.YES.getCode())) {
                        flag = true;
                    }
                    //已付款并且虚拟订单已过期且不支持退款或退款完成
                    if (entity.getOrderStatus().equals(CommonType.orderStatus.PAID.getCode())
                            && !DateUtils.compareDate2(entity.getPeriodOfValidity())
                            && (entity.getPastDue().equals(0) || entity.getOrderRefundStatus().equals(CommonType.commonStatus.OTHER.getCode()))) {
                        flag = true;
                    }
                    //已付款并且虚拟订单已校验
                    if (entity.getOrderStatus().equals(CommonType.orderStatus.PAID.getCode())
                            && entity.getIsCancel().equals(CommonType.commonStatus.NO.getCode())) {
                        flag = true;
                    }

                }

                status = flag;
            }
            if (status) {
                return ResponseResult.success();
            } else {
                return ResponseResult.fail();
            }
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult queryExchangeList(Map<String, Object> param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.get("token").toString());
        if (null != userInfo) {
            try {
                //将对象转换为map
                Map data = ParseMapUtils.beanToMap(param);
                //分页查询数据
                IPage<OrderBaseEntity> page = this.baseMapper.queryExchangeList(new Query<OrderBaseEntity>().getPage(data), param);

                return ResponseResult.success(PageUtils.getPage(page));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    /**
     * 发货
     *
     * @param map
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult piLiangFahuoShipments(Map<Object, Object> map, Integer isPiLiang) throws TransactionException {
        ResponseResult rr = new ResponseResult();
        log.info("-----para-----" + map.toString());
        String orderId = (String) map.get("orderId");
        //校验订单是否退款
        Integer count = this.baseMapper.selectCount(new LambdaQueryWrapper<OrderBaseEntity>()
                                        .eq(OrderBaseEntity::getOrderId,orderId)
                                        .eq(OrderBaseEntity::getOrderReturnStatus,CommonType.orderReturnStatus.NO_RETURNS.getCode())
                                        .eq(OrderBaseEntity::getOrderRefundStatus,CommonType.orderRefundStatus.NO_REFUND.getCode()));
        if (count == 0) {
            return ResponseResult.fail(BizCodeEnume.ORDER_HAVE_REFUND_RETURN);
        }
        boolean isUpdateSuccessByOrderGoods = false;
        boolean isUpdateSuccessByOrderBase = false;
        try {
            // 商家所用发货地址id
            Integer shippingAddressId = Integer.parseInt(map.get("shippingAddressId").toString());
            // 发货人姓名
            String orderSellerName = (String) map.get("orderSellerName");
            // 发货人地址
            String orderSellerAddress = (String) map.get("orderSellerAddress");
            // 发货人联系方式
            String orderSellerContact = (String) map.get("orderSellerContact");
            // 配送时间
            String orderShippingTime = DateUtils.getTime();
            // 配送公司ID
            Integer orderShippingExpressId = Integer.parseInt(map.get("orderShippingExpressId").toString());
            // 物流单号
            String orderShippingCode = (String) map.get("orderShippingCode");
            // 商品id
            String goodsId = (String) map.get("goodsId");
            // 查询订单信息 如状态，退货退款状态，收货人手机号
            OrderBaseEntity qos = this.baseMapper.selectOne(new LambdaQueryWrapper<OrderBaseEntity>()
                    .eq(OrderBaseEntity::getOrderId, orderId));
            String receiverPhone = qos.getOrderReceiverContact();
            //查询快递信息
            ResponseResult express = baseServiceClient.getBaseExpressInfoById(orderShippingExpressId);
            BaseExpressDTO shipperCode = JSONObject.parseObject(JSON.toJSONString(express.getData()), BaseExpressDTO.class);
            if (orderShippingExpressId.equals(47)) {
                // 获取手机号后四位
                String phoneNumber = receiverPhone.substring(7, 11);
                // 顺丰快递物流号
                orderShippingCode = orderShippingCode + ":" + phoneNumber;
            }
            // 物流发货备注
            String orderShippingMessage = map.get("orderShippingMessage") == null ?
                    "" : (String) map.get("orderShippingMessage");
            Integer orderStatus = 4;
            // 商品订单是否已经发货。1-是，0-否，默认0(orderGoods)
            Integer orderGoodsIdDeliver = 1;
            Map<String, Object> mapGoods = new HashMap<>();
            mapGoods.put("orderId", orderId);
            mapGoods.put("orderStatus", orderStatus);
            //updateByOrderBase 参数去除
            mapGoods.put("orderGoodsIdDeliver", orderGoodsIdDeliver);
            mapGoods.put("orderSellerName", orderSellerName);
            mapGoods.put("orderSellerAddress", orderSellerAddress);
            mapGoods.put("orderSellerContact", orderSellerContact);
            mapGoods.put("orderShippingTime", orderShippingTime);
            mapGoods.put("orderShippingExpressId", orderShippingExpressId);
            mapGoods.put("orderShippingCode", orderShippingCode);
            mapGoods.put("orderShippingMessage", orderShippingMessage);
            mapGoods.put("goodsId", goodsId);
            if (qos.getOrderStatus() == 3 && qos.getOrderRefundStatus() .equals(CommonType.orderRefundStatus.REFUNDING.getCode())) {
                rr.setCode(BizCodeEnume.ORDER_AFTER_SALES.getCode());
                rr.setMessage(BizCodeEnume.ORDER_AFTER_SALES.getMsg());
            } else if (qos.getOrderStatus() == 6 && qos.getOrderRefundStatus() .equals(CommonType.orderRefundStatus.REFUND_COMPLETED.getCode())) {
                rr.setCode(BizCodeEnume.ORDER_AFTER_SALES_COMPLETION.getCode());
                rr.setMessage(BizCodeEnume.ORDER_AFTER_SALES_COMPLETION.getMsg());
            } else {
                if (CommonType.commonStatus.YES.getCode().equals(isPiLiang)) {
                    isUpdateSuccessByOrderGoods = orderGoodsMapper.piLiangupdateByOrderGoods(mapGoods);
                } else {
                    isUpdateSuccessByOrderGoods = orderGoodsMapper.updateByOrderGoods(mapGoods);
                }
                isUpdateSuccessByOrderBase = this.baseMapper.updateByOrderBase(mapGoods);
                if (isUpdateSuccessByOrderGoods && isUpdateSuccessByOrderBase) {
                    // 分佣订单售后时间更新
                    updateOrderAfterSale(orderId);
                    rr.setCode(CommonStatusEnum.SUCCESS.getCode());
                    rr.setMessage("发货成功！");
                    payMentServiceClient.changeConsumeRecord(orderId);
                    if (CommonType.commonStatus.YES.getCode().equals(isPiLiang)) {
                        // 信息
                        rr = businessServiceClient.queryShippingAddress(shippingAddressId);
                        String senderAddress = (String) rr.getData();
                        String requestData = sendKdniaoMessage(senderAddress, qos, orderShippingCode,
                                orderSellerName, orderSellerContact, orderSellerAddress, shipperCode);
                        String results = KdniaoSubscribeAPI.orderTracesSubByJson(requestData);
                        System.out.println("-----LogisticsTrackingReturnResults-----" + results);
                    }
                    //发货成功短信提醒
                    try {
                        //获取店铺名称
                        String shopName = qos.getShopName();
                        //设置快递名称
                        String ShippingExpressName = shipperCode.getExpressName();
                        Map<String, String> paraMap = new HashMap<>();
                        paraMap.put("userMobile", receiverPhone);
                        paraMap.put("shopName", shopName);
                        paraMap.put("orderShippingCode", orderShippingCode);
                        paraMap.put("ShippingExpressname", ShippingExpressName);
                        thirdPartyServiceClient.shipments(paraMap);

                        //发送站内信通知
                        PlatformMessageVO platformMessage = new PlatformMessageVO();
                        platformMessage.setCreateTime(new Date());
                        platformMessage.setUserId(qos.getBuyerUserId());//买家id
                        platformMessage.setMessageContent("你的订单" + orderId + "已发货");
                        platformMessage.setMessageTitle("订单发货提醒");
                        platformMessage.setCreater(shopName);
                        this.baseMapper.insertMessage(platformMessage);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    rr.setCode(BizCodeEnume.UPDATE_ERROR.getCode());
                    rr.setMessage(BizCodeEnume.UPDATE_ERROR.getMsg());
                }
            }
        } catch (Exception e) {
            rr.setCode(BizCodeEnume.SYSTEM_ERROR.getCode());
            rr.setMessage(BizCodeEnume.SYSTEM_ERROR.getMsg());
            log.info("ShipmentsErrorResults:" + e.getMessage());
            GlobalTransactionContext.reload(RootContext.getXID()).rollback();
        } finally {
//            Integer orderStatus = this.baseMapper.queryShipmentsOrderStatus(orderId);
//            if (null != orderStatus && orderStatus != 4) {
//                this.baseMapper.updateOrderStatusForBase(orderId);
//                orderGoodsMapper.updateOrderStatusForGoods(orderId);
//            }
        }
        return rr;
    }


    public ResponseResult updateOrderAfterSale(String orderId){
        try {
            OrderCommissionVO orderCommission = orderCommissionMapper.selectByPrimaryKey(orderId);
            if (null != orderCommission) {
                ResponseResult resultResp = baseServiceClient.queryGoodsVkSet();
                GoodsVkSetVO goodsVkSet = JSON.parseObject(JSON.toJSONString(resultResp.getData()), GoodsVkSetVO.class);
                this.baseMapper.updateOrderAfterSaleTime(orderId, DateUtils.getAfterDate(goodsVkSet.getAfterSalesDays()));
            }
            return ResponseResult.success();
        }catch (Exception e){
            log.error(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
        }
    }

    /**
     * 快递鸟传值拼接
     */
    public String sendKdniaoMessage(String senderAddress, OrderBaseEntity qos, String orderShippingCode,
                                    String orderSellerName, String orderSellerContact, String orderSellerAddress, BaseExpressDTO shipperCode) {
        String requestData = null;
        try {
            MerchantsAddressDTO merchantsAddress = JSON.parseObject(senderAddress, MerchantsAddressDTO.class);
            SubscriptionVO sp = new SubscriptionVO();
            sp.setShipperCode(shipperCode.getExpressPinyin());
            sp.setLogisticCode(orderShippingCode);
            SenderDTO senderPara = new SenderDTO();
            senderPara.setName(orderSellerName);
            senderPara.setMobile(orderSellerContact);
            senderPara.setAddress(orderSellerAddress);
            senderPara.setProvinceName(merchantsAddress.getShippingAddressProvince());
            senderPara.setCityName(merchantsAddress.getShippingAddressCity());
            senderPara.setExpAreaName(merchantsAddress.getShippingAddressArea());
            // 推送参数
            String buyerUserId = qos.getBuyerUserId();
            Map<String, Integer> districtMap = new HashMap<String, Integer>();
            districtMap.put("provinceId", qos.getOrderReceiverProvinceId());
            districtMap.put("cityId", qos.getOrderReceiverCityId());
            districtMap.put("areaId", qos.getOrderReceiverAreaId());
            List<String> region = baseServiceClient.queryRegionName(districtMap);
            ReceiverDTO rp = new ReceiverDTO();
            rp.setName(qos.getOrderReceiverName());
            rp.setMobile(qos.getOrderReceiverContact());
            rp.setAddress(qos.getOrderReceiverAddress());
            rp.setProvinceName(region.get(0));
            rp.setCityName(region.get(1));
            rp.setExpAreaName(region.get(2));
            sp.setSenderPara(senderPara);
            sp.setReceiverPara(rp);
            requestData = sp.toString();
        } catch (Exception e) {
            log.info("-----sendKdniaoMessage-----" + e.getMessage());
        }
        return requestData;
    }
    @Override
    public ResponseResult totalTurnoverOfThePlatform(Map<String, Object> map) {
        String token = (String) map.get("token");
        UserInfoVO info = ParseTokenUtils.getPlatformUser(token);
        if (info != null) {
            try {
                // 类型:1、全部，2、当日，3、本周，4、本月，5、年度
                Integer type = (Integer) map.get("type");
                BigDecimal money = new BigDecimal(0);
                if (type == 1) {
                    money = this.baseMapper.queryAllSales();
                } else if (type == 2) {
                    money = this.baseMapper.queryTodaySales();
                } else if (type == 3) {
                    money = this.baseMapper.queryWeekSales();
                } else if (type == 4) {
                    money = this.baseMapper.queryMonthSales();
                } else {
                    money = this.baseMapper.queryYearSales();
                }
                money = money.setScale(2, BigDecimal.ROUND_HALF_UP);
                return ResponseResult.success(money);
            } catch (Exception e) {
                return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
    }

    @Override
    public ResponseResult storeRanking(Map<String, Object> map) {
        String token = (String) map.get("token");
        UserInfoVO info = ParseTokenUtils.getPlatformUser(token);
        if (info != null) {
            try {
                Integer type = (Integer) map.get("type");
                List<StoreParaVO> storeList = null;
                if (type == 1) {
                    storeList = this.baseMapper.queryAllStore();
                } else if (type == 2) {
                    storeList = this.baseMapper.queryTodayStore();
                } else if (type == 3) {
                    storeList = this.baseMapper.queryWeekStore();
                } else if (type == 4) {
                    storeList = this.baseMapper.queryMonthStore();
                } else {
                    storeList = this.baseMapper.queryYearStore();
                }
                return ResponseResult.success(storeList);
            } catch (Exception e) {
                return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
    }

    @Override
    public ResponseResult logisticsInformation(Map<String, Object> map) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());
        if(null == userInfo){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        String userId = userInfo.getUserId();
        map.put("userId",userId);
        IPage<OrderListVO> page = this.baseMapper.selByOrderBase(new Query<OrderListVO>().getPage(map),map);
        List<OrderListVO> orderList = page.getRecords();
        for (int i = 0; i < orderList.size(); i++) {
            Integer goodsNum = 0;
            BigDecimal goodsTotalPrice = new BigDecimal(0);
            String orderId = orderList.get(i).getOrderId();
            List<GoodsDetailsListVO> goodsDetailsList = this.baseMapper.queryGoodsList1(orderId);
            orderList.get(i).setGoodsDetailsList(goodsDetailsList);
            for (int j = 0; j < goodsDetailsList.size(); j++) {
                // 计算共有几件商品
                Integer goodsnum = goodsDetailsList.get(j).getOrderGoodsNum();
                goodsNum += goodsnum;
                orderList.get(i).setGoodsNum(goodsNum);
                // 计算商品总价
                BigDecimal goodsprice = goodsDetailsList.get(j).getOrderGoodsAmount();
                goodsTotalPrice = goodsTotalPrice.add(goodsprice);
                orderList.get(i).setOrderTotalPrice(goodsTotalPrice);
            }
        }
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult queryGateOrders(Map<String, Object> map) {
        String token = (String) map.get("token");
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
        if (null != ui) {
            String userId = null;
            try {
                // 发送人id
                userId = ui.getUserId();
                // 订单状态
                Integer orderStatus = (Integer) map.get("orderStatus");
				/*
				订单状态 1.待付款 2.已付款 3.待发货 4.已发货 5.已签收 6.确认收货 7.取消 8.退款中 9.已退款 11.待自提
				 */
                if (orderStatus == 2) {
                    // 待付款
                    map.put("orderStatusNum",1);
                } else if (orderStatus == 4) {
                    //
                    map.put("orderStatusNum",4);
                } else if (orderStatus == 5) {
                    // 已完成
                    map.put("orderStatusNum",6);
                }
                map.put("userId",userId);

                IPage<OrderListVO> page = this.baseMapper.queryGateOrdersList(new Query<OrderListVO>().getPage(map),map);
                List<OrderListVO> orderList = page.getRecords();
                // 商品总价
                BigDecimal paymentPrice = new BigDecimal(0);
                for (int i = 0; i < orderList.size(); i++) {
                    Integer goodsNum = 0;
                    String orderId = orderList.get(i).getOrderId();
                    //feign调用根据门店ID查询门店名称
                    if(orderList.get(i).getOrderGateShopId() != null) {
                        String resultGateName = businessServiceClient.queryGateStoreName(orderList.get(i).getOrderGateShopId());
                        orderList.get(i).setOrderGateName(resultGateName);
                    }
                    List<GoodsDetailsListVO> goodsDetailsList = orderGoodsMapper.queryGoodsList(orderId);
                    orderList.get(i).setGoodsDetailsList(goodsDetailsList);
                    // 退款状态
                    Integer orderRefundStatus = orderList.get(i).getOrderRefundStatus();
                    // 退货状态
                    Integer orderReturnStatus = orderList.get(i).getOrderReturnStatus();
                    // 订单状态
                    Integer normalStatus = orderList.get(i).getOrderStatus();
                    // 1.待付款  4.已发货  6.确认收货 7.取消 8.退款中 9.已退款
                    Integer status =  normalStatus;
                    // 存放最新状态
                    orderList.get(i).setOrderStatus(status);
                    for (int j = 0; j < goodsDetailsList.size(); j++) {
                        // 计算共有几件商品
                        Integer goodsnum = goodsDetailsList.get(j).getOrderGoodsNum();
                        goodsNum += goodsnum;
                        orderList.get(i).setGoodsNum(goodsNum);

                        // 计算商品总价
                        // 单个商品价格
                        BigDecimal orderGoodsAmount = goodsDetailsList.get(j).getOrderGoodsAmount();
                        paymentPrice = paymentPrice.add(orderGoodsAmount).setScale(2, BigDecimal.ROUND_UP);

                    }
                    // 每家店铺总计价格
                    orderList.get(i).setShopOrderTotalPrice(paymentPrice);
                    // 退款实际价格
                    orderList.get(i).setRefundRealPrice(orderList.get(i).getOrderGoodsAmount());
                    // 总付款价格
                    orderList.get(i).setOrderTotalPrice(orderList.get(i).getOrderPaymentAmount());

                }
                page.setRecords(orderList);
                return ResponseResult.success(PageUtils.getPage(page));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
    }

    @Override
    public ResponseResult queryOrders(Map<String, Object> map) {
        String token = (String) map.get("token");
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
        if (null != ui) {
            try {
                // 发送人id
                String userId = ui.getUserId();
                // 订单状态
                Integer orderStatus = (Integer) map.get("orderStatus");
                Integer virtualGoods = (Integer) map.get("virtualGoods");
                Integer orderStatusNum = null;
                String allOrders = null;
                if (orderStatus == 1) {
                    // 全部订单
                    allOrders = "' '";
                } else if (orderStatus == 2) {
                    // 待付款
                    orderStatusNum = 1;
                } else if (orderStatus == 3) {
                    // 待发货
                    orderStatusNum = 3;
                } else if (orderStatus == 4) {
                    // 待收货
                    orderStatusNum = 4;
                } else if (orderStatus == 5) {
                    // 已取消
                    orderStatusNum = 7;
                }
                map.put("orderStatusNum", orderStatusNum);
                map.put("userId", userId);

                IPage<OrderListVO> page = this.baseMapper.queryOrderListByPhone(new Query<OrderListVO>().getPage(map), map);
                List<OrderListVO> orderList = page.getRecords();
                // 商品总价
                BigDecimal paymentPrice = new BigDecimal(0);
                for (OrderListVO orderListVO : orderList) {
                    //判断是否可以再申请售后
                    Integer platformInterventionId = orderListVO.getPlatformInterventionId();
                    Integer interventionState = orderListVO.getInterventionState();
                    Integer processingResults = orderListVO.getProcessingResults();
                    Integer returnMethodType = orderListVO.getReturnMethodType();
                    if (platformInterventionId != null && interventionState == 2 && processingResults == 0 && returnMethodType == 1) {
                        orderListVO.setPlatformAudit(1);
                    } else if (platformInterventionId != null && interventionState == 2 && processingResults == 0 && (returnMethodType == 2 || returnMethodType == 3)) {
                        orderListVO.setPlatformAudit(2);
                    } else {
                        orderListVO.setPlatformAudit(0);
                    }
                    Integer goodsNum = 0;
                    String orderId = orderListVO.getOrderId();
                    List<GoodsDetailsListVO> goodsDetailsList = orderGoodsMapper.queryGoodsList(orderId);
                    orderListVO.setGoodsDetailsList(goodsDetailsList);
                    // 退款状态
                    Integer orderRefundStatus = orderListVO.getOrderRefundStatus();
                    // 退货状态
                    Integer orderReturnStatus = orderListVO.getOrderReturnStatus();
                    // 订单状态
                    Integer normalStatus = orderListVO.getOrderStatus();
                    // 1.线上支付  2.线下支付 3.货到付款
                    Integer paymentCode = orderListVO.getPaymentCode();
                    Integer status = null;// 涉及退款退货订单状态
                    if (normalStatus == 3 || (null != virtualGoods && 0 == virtualGoods && 4 == normalStatus)) {
                        // 未发货状态
                        if (orderRefundStatus == 1) {
                            // 未发货退款中
                            status = 22;
                        } else if (orderRefundStatus == 2) {
                            // 商家拒绝或审核通过，继续发货，但不可再次申请退款
                            status = 26;
                        } else if (orderRefundStatus == 0 && null != virtualGoods && 0 == virtualGoods) {
                            status = normalStatus;
                        } else {
                            status = 3;
                        }
                    } else if (normalStatus == 6) {
                        // 已完成状态
                        if (orderRefundStatus == 1) {
                            // 收货退款中
                            status = 23;
                        } else if (orderRefundStatus == 2) {
                            status = 25;
                        } else if (orderRefundStatus == 0 && orderReturnStatus == 0) {
                            status = 6;
                        } else if (orderReturnStatus == 1) {
                            // 收货退货中
                            status = 24;
                        } else if (orderReturnStatus == 2) {
                            status = 25;
                        } else if (orderReturnStatus == 0 && orderRefundStatus == 0) {
                            status = 6;
                        } else {
                            status = 6;
                        }
                        if (null != orderListVO.getOrderLastReturnTime() && DateUtils.compareDate(orderListVO.getOrderLastReturnTime(), DateUtils.getNowDateToString())) {
                            // 订单超过完成时间不可售后
                            status = 27;
                        }
                    } else {
                        status = normalStatus;
                    }
                    // 存放最新状态
                    orderListVO.setOrderStatus(status);
                    if (null != paymentCode && 2 == paymentCode) {
                        //查询线下支付的审核状态
                        OdbPaymentVocherVO PaymentVocherPo = orderPaymentVocherMapper.queryPaymentVocher(orderId);
                        if (null != PaymentVocherPo) {
                            orderListVO.setReviewStatus(PaymentVocherPo.getReviewStatus());
                        }
                    }
                    for (GoodsDetailsListVO goodsDetailsListVO : goodsDetailsList) {
                        // 计算共有几件商品
                        Integer goodsnum = goodsDetailsListVO.getOrderGoodsNum();
                        goodsNum += goodsnum;
                        orderListVO.setGoodsNum(goodsNum);
                        //若为待付款订单，对限时秒杀商品添加距离付款时间
                        if (1 == status) {
                            Integer goodsId = goodsDetailsListVO.getGoodsId();
                            Integer seckillId = this.baseMapper.queryCountForSeckillGoods(goodsId);
                            if (null != seckillId && seckillId > 0) {
                                //取消时间 单位分钟
                                Integer cancelTime = this.baseMapper.queryCancelTime(seckillId);
                                if (null != cancelTime && cancelTime > 0) {
//                                    String orderCreateTime = orderList.get(i).getOrderCreateTime();
                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    try {
                                        Date orderCreateTimeDate = orderListVO.getOrderCreateTime();
                                        Calendar cal = Calendar.getInstance();
                                        cal.setTime(orderCreateTimeDate);
                                        cal.add(Calendar.MINUTE, cancelTime);
                                        Date orderCancelTime = cal.getTime();
                                        if (new Date().before(orderCancelTime)) {
                                            Long overplusTime = orderCancelTime.getTime();
                                            if (orderListVO.getOrderCancelTime() == null) {
                                                orderListVO.setOrderCancelTime(overplusTime);
                                            } else if (orderListVO.getOrderCancelTime() > overplusTime) {
                                                orderListVO.setOrderCancelTime(overplusTime);
                                            }
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                        // 计算商品总价
                        // 单个商品价格
                        BigDecimal orderGoodsAmount = goodsDetailsListVO.getOrderGoodsAmount();
                        paymentPrice = paymentPrice.add(orderGoodsAmount).setScale(2, RoundingMode.UP);
                    }
                    if (orderListVO.getOrderBuyId() != null) {
                        ResponseResult orderPintuanMarkEntity = activityServiceClient.querySurplusNum(orderListVO.getOrderBuyId());
                        if (!ObjectUtils.isEmpty(orderPintuanMarkEntity.getData())) {
                            Integer numberesultemaining = Integer.valueOf(orderPintuanMarkEntity.getData().toString());
                            orderListVO.setNumberRemaining(numberesultemaining);
                        }
                    }
                    // 每家店铺总计价格
                    orderListVO.setShopOrderTotalPrice(paymentPrice);
                    // 退款实际价格
                    orderListVO.setRefundRealPrice(orderListVO.getOrderGoodsAmount());// 总付款价格

                    orderListVO.setOrderTotalPrice(orderListVO.getOrderPaymentAmount());

                }
                page.setRecords(orderList);
                return ResponseResult.success(PageUtils.getPage(page));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(), BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(), BizCodeEnume.SYSTEM_ERROR.getMsg());
    }

    @Override
    public ResponseResult queryOrderByEvaluation(Map<String, Object> map) {
        String token = (String) map.get("token");
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
        if (null != ui) {
            String userId = ui.getUserId();
            // 待评价
            Integer waitingEvaluation = 0;
            // 已完成
            Integer offTheStocks = 6;
            map.put("userId",userId);
            map.put("waitingEvaluation",waitingEvaluation);
            map.put("offTheStocks",offTheStocks);
            IPage<OrderListVO> page = this.baseMapper.queryWaitingEvaluationOrder(new Query<OrderListVO>().getPage(map),map);
            List<OrderListVO> orderList = page.getRecords();
            BigDecimal paymentPrice = new BigDecimal(0);
            for (int i = 0; i < orderList.size(); i++) {
                Integer goodsNum = 0;
                String orderId = orderList.get(i).getOrderId();
                // 查询待评价商品信息
                List<GoodsDetailsListVO> goodsDetailsList = orderGoodsMapper.queryGoodsList(orderId);
                orderList.get(i).setGoodsDetailsList(goodsDetailsList);
                // 退款状态
                Integer orderRefundStatus = orderList.get(i).getOrderRefundStatus();
                // 退货状态
                Integer orderReturnStatus = orderList.get(i).getOrderReturnStatus();
                // 订单状态
                Integer normalStatus = orderList.get(i).getOrderStatus();
                // 涉及退款退货订单状态
                Integer status = null;
                if (normalStatus == 3) {
                    // 未发货状态
                    if (orderRefundStatus == 1) {
                        // 未发货退款中
                        status = 22;
                    } else if (orderRefundStatus == 2) {
                        // 商家拒绝或审核通过，继续发货，但不可再次申请退款
                        status = 26;
                    } else if (orderRefundStatus == 0) {
                        status = 3;
                    }
                } else if (normalStatus == 6) {
                    // 已完成状态
                    if (orderRefundStatus == 1) {
                        // 收货退款中
                        status = 23;
                    } else if (orderRefundStatus == 2) {
                        status = 25;
                    } else if (orderRefundStatus == 0 && orderReturnStatus == 0) {
                        status = 6;
                    } else if (orderReturnStatus == 1) {
                        // 收货退货中
                        status = 24;
                    } else if (orderReturnStatus == 2) {
                        status = 25;
                    } else if (orderReturnStatus == 0 && orderRefundStatus == 0) {
                        status = 6;
                    }
                } else {
                    status = normalStatus;
                }
                // 存放最新状态
                orderList.get(i).setOrderStatus(status);
                for (int j = 0; j < goodsDetailsList.size(); j++) {
                    // 计算共有几件商品
                    Integer goodsnum = goodsDetailsList.get(j).getOrderGoodsNum();
                    goodsNum += goodsnum;
                    orderList.get(i).setGoodsNum(goodsNum);

                    // 计算商品总价
                    // 单个商品价格
                    BigDecimal orderGoodsAmount = goodsDetailsList.get(j).getOrderGoodsAmount();
                    paymentPrice = paymentPrice.add(orderGoodsAmount).setScale(2, BigDecimal.ROUND_UP);

                }
                // 退款实际价格
                orderList.get(i).setRefundRealPrice(orderList.get(i).getOrderGoodsAmount());
                // 总付款价格
                orderList.get(i).setOrderTotalPrice(orderList.get(i).getOrderPaymentAmount());
            }
            page.setRecords(orderList);
            return ResponseResult.success(PageUtils.getPage(page));
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
    }

    @Override
    public ResponseResult virtualOrders(Map<String, Object> map) {
        String token = (String) map.get("token");
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (!isExistToken) {
            return ResponseResult.fail(10086, "token失效，请重新获取！");
        }
            try {
                UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
                String shopId = ui.getShopId();
                Integer isCancel = null;
                if (map.get("isCancel") != null) {
                    isCancel = Integer.parseInt(map.get("isCancel").toString());
                }
                String userName = (String) map.get("userName");

                String orderNum = (String) map.get("orderNum");

                String goodsName = (String) map.get("goodsName");

                String orderStartTime = (String) map.get("orderStartTime");

                String orderEndTime = (String) map.get("orderEndTime");

                Integer status = Integer.parseInt(map.get("status") + "");
                String allOrderStatus = null;
                Integer otherOrderStatus = null;
                if (status == 1) {
                    allOrderStatus = "' '";
                } else if (status == 2) {
                    // 待付款
                    otherOrderStatus = 1;
                } else if (status == 3) {
                    // 已付款
                    otherOrderStatus = 3;
                } else if (status == 4) {
                    // 已发货
                    otherOrderStatus = 4;
                } else if (status == 5) {
                    // 已完成
                    otherOrderStatus = 6;
                } else if (status == 6) {
                    // 已取消
                    otherOrderStatus = 7;
                }else if (status == 12) {
                    // 虚拟订单 已过期
                    otherOrderStatus = 12;
                }
                Page<OrderDetailsVO> page = new Page<>(Integer.parseInt(map.get("page") + ""),Integer.parseInt(map.get("limit") + ""));
                map.put("shopId",shopId);
                map.put("virtualGoods",0);
                map.put("isCancel",isCancel);
                map.put("allOrderStatus",allOrderStatus);
                map.put("otherOrderStatus",otherOrderStatus);
                map.put("userName",userName);
                map.put("orderNum",orderNum);
                map.put("goodsName",goodsName);
                map.put("orderStartTime",orderStartTime);
                map.put("orderEndTime",orderEndTime);
                IPage<OrderDetailsVO> orderDetails = this.baseMapper.queryVirtualOrderBase(page,map);
                for (OrderDetailsVO record : orderDetails.getRecords()) {
                    String orderId = record.getOrderId();
                    // 退款状态
                    Integer orderRefundStatus = record.getOrderRefundStatus();
                    // 退货状态
                    Integer orderReturnStatus = record.getOrderReturnStatus();
                    // 订单状态
                    Integer normalStatus = record.getOrderStatus();
                    // 涉及退款退货订单状态
                    Integer Orderstatus = null;
                    if (normalStatus == 3) {
                        // 未发货状态
                        if (orderRefundStatus == 1) {
                            // 未发货退款中
                            Orderstatus = 22;
                        } else if (orderRefundStatus == 2) {
                            // 商家拒绝或审核通过，继续发货，但不可再次申请退款
                            Orderstatus = 26;
                        } else if (orderRefundStatus == 0) {
                            Orderstatus = 3;
                        }
                    } else if (normalStatus == 6) {
                        // 已完成状态
                        if (orderRefundStatus == 1) {
                            // 收货退款中
                            Orderstatus = 23;
                        } else if (orderRefundStatus == 2) {
                            Orderstatus = 25;
                        } else if (orderRefundStatus == 0 && orderReturnStatus == 0) {
                            Orderstatus = 6;
                        } else if (orderReturnStatus == 1) {
                            // 收货退货中
                            Orderstatus = 24;
                        } else if (orderReturnStatus == 2) {
                            Orderstatus = 25;
                        } else if (orderReturnStatus == 0 && orderRefundStatus == 0) {
                            Orderstatus = 6;
                        }
                    } else {
                        Orderstatus = normalStatus;
                    }
                    record.setOrderStatus(Orderstatus);// 存放最新状态
                    List<GoodsDetailsVO> queryOrderDetails = this.baseMapper.queryOrders(orderId);
                    if (queryOrderDetails == null) {
                        return ResponseResult.fail(2,"订单为空！");
                    }
                    record.setGoodsDetails(queryOrderDetails);
                }
                return ResponseResult.success(PageUtils.getPage(orderDetails));
            } catch (Exception e) {
                return ResponseResult.fail(500, "SoldOrdersErrorResults:" + e.getMessage());
            }
    }

    @Override
    public ResponseResult queryGateShopOrders(Map<String, Object> map) {
        String token = (String) map.get("token");
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (!isExistToken) {
            return ResponseResult.fail(10086, "token失效，请重新获取！");
        }

        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
        // 订单状态
        Integer orderStatus = (Integer) map.get("orderStatus");
        Integer orderStatusNum = null;
        if (orderStatus == 1) {
            // 全部订单
        } else if (orderStatus == 2) {
            // 待付款
            orderStatusNum = 1;
        } else if (orderStatus == 3) {
            // 待自提
            orderStatusNum = 4;
        } else if (orderStatus == 4) {
            //  以自提
            orderStatusNum = 6;
        }
        map.put("orderStatusNum", orderStatusNum);
        map.put("orderGateShopId", ui.getShopId());
        Page<GateShopOrdersVO> page = new Page<>((Integer) map.get("page"), (Integer) map.get("limit"));
        IPage<GateShopOrdersVO> orderList = this.baseMapper.queryGateShopOrders(page, map);
        return ResponseResult.success(PageUtils.getPage(orderList));
    }

    @Override
    public ResponseResult webGateShopCancelOrder(Map<String, Object> map) {
        String token = (String) map.get("token");
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (!isExistToken) {
            return ResponseResult.fail(10086, "token失效，请重新获取！");
        }
        String redeemCode = (String) map.get("redeemCode");

        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
        try {
            if (null == ui.getShopId()) {
                return ResponseResult.fail(10086, "暂无权限");
            }
            Map<String, Object> stringObjectMap = this.baseMapper.queryGateShopCancelOrderDetails(redeemCode, ui.getShopId());
            if (null == stringObjectMap) {
                return ResponseResult.fail(2, "抱歉，该核销码不是本店的！");
            }
            //是否核销  0是 1否 2已过期
            if (1 == (Long) stringObjectMap.get("is_cancel")) {
                return ResponseResult.success("未核销", stringObjectMap);
            } else if (0 == (Long) stringObjectMap.get("is_cancel")) {
                return ResponseResult.success("订单已核销", stringObjectMap);
            } else if (2 == (Long) stringObjectMap.get("is_cancel")) {
                return ResponseResult.success("订单过期", stringObjectMap);
            }
            return ResponseResult.fail(500, "系统错误", stringObjectMap);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(500, e.getMessage());
        }
    }

    @Override
    public ResponseResult cancelGateShopOrder(Map<String, Object> map) {
        String token = (String) map.get("token");
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (!isExistToken) {
            return ResponseResult.fail(10086, "token失效，请重新获取！");
        }
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
        try {
            if (null == ui.getShopId()) {
                return ResponseResult.fail(10086, "暂无权限");
            }
            String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            String redeemCode = (String) map.get("redeemCode");
            OrderDetailsVO orderDetails = this.baseMapper.queryGateShopOrderDetails(redeemCode, ui.getShopId());
            if (orderDetails.getIsCancel() == 0) {
                return ResponseResult.fail(2, "此订单已经核销！");
            }
            Integer integer = this.baseMapper.updateGateShopOrderCancel(redeemCode, currentTime, orderDetails.getOrderId(), ui.getShopId());
            if (integer > 0) {
                return ResponseResult.success();
            }
            return ResponseResult.fail(2, "操作失败");
        } catch (Exception e) {
            log.info("JsonProcessingExceptionError:" + e.getMessage());
            return ResponseResult.fail(500, e.getMessage());
        }
    }

    @Override
    public ResponseResult queryVirtualGateShopOrders(Map<String, Object> map) {
        String token = String.valueOf(map.get("token"));
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
        if (ui == null) {
            return ResponseResult.fail(10086, "token失效，请重新获取！");
        }
            try {
                if (null == ui.getShopId()) {
                    return ResponseResult.fail(10086, "暂无权限");
                }
                //订单状态
                Integer status = (Integer) map.get("status");
                String allOrderStatus = null;
                Integer otherOrderStatus = null;
                if (status == 1) {
                    allOrderStatus = "' '";
                } else if (status == 2) {
                    // 待付款
                    otherOrderStatus = 1;
                } else if (status == 3) {
                    // 已付款
                    otherOrderStatus = 3;
                } else if (status == 4) {
                    // 已发货
                    otherOrderStatus = 4;
                } else if (status == 5) {
                    // 已完成
                    otherOrderStatus = 6;
                } else if (status == 6) {
                    // 已取消
                    otherOrderStatus = 7;
                }
                map.put("otherOrderStatus",otherOrderStatus);
                map.put("shopId",ui.getShopId());
                Page<VirtualGateShopOrderVO> page = new Page<>(Integer.parseInt(map.get("page") + ""),
                        Integer.parseInt(map.get("limit") + ""));
                IPage<VirtualGateShopOrderVO> orderList = this.baseMapper.queryVirtualGateShopOrders(page, map);
                return ResponseResult.success(PageUtils.getPage(orderList));
            } catch (Exception e) {
                log.info("SoldOrdersErrorResults:" + e.getMessage());
                return ResponseResult.fail(500, e.getMessage());
            }
    }

    @Override
    public ResponseResult shopGateTakeOrder(Map<String, Object> map) {
        String token = (String) map.get("token");
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (!isExistToken) {
            return ResponseResult.fail(10086, "token失效，请重新获取！");
        }
        try {
            UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
            Integer shopId = Integer.valueOf(ui.getShopId());
            String username = (String) map.get("userName");
            String userName = null;
            if (username == "") {
                userName = "";
            } else {
                userName = "'" + username + "'";
            }
            String ordernum = (String) map.get("orderNum");
            String orderNum = null;
            if (ordernum == "") {
                orderNum = "";
            } else {
                orderNum = "'" + ordernum + "'";
            }
            String goodsname = (String) map.get("goodsName");
            String goodsName = null;
            if (goodsname == "") {
                goodsName = "";
            } else {
                goodsName = "'" + goodsname + "'";
            }
            String orderstarttime = (String) map.get("orderStartTime");
            String orderStartTime = null;
            if (orderstarttime == "") {
                orderStartTime = "";
            } else {
                orderStartTime = "'" + orderstarttime + "'";
            }
            String orderendtime = (String) map.get("orderEndTime");
            String orderEndTime = null;
            if (orderendtime == "") {
                orderEndTime = "";
            } else {
                orderEndTime = "'" + orderendtime + "'";
            }
            String shopGateName = null;
            if (null != map.get("shopGateName") && "" != map.get("shopGateName") ) {
                shopGateName = (String)map.get("shopGateName");
            }
            Integer status = Integer.parseInt(map.get("status") + "");
            String allOrderStatus = null;
            Integer otherOrderStatus = null;
            if (status == 1) {
                allOrderStatus = "' '";
            } else if (status == 2) {
                // 待付款
                otherOrderStatus = 1;
            } else if (status == 3) {
                // 已付款
                otherOrderStatus = 3;
            } else if (status == 4) {
                // 已发货
                otherOrderStatus = 4;
            } else if (status == 5) {
                // 已完成
                otherOrderStatus = 6;
            } else if (status == 6) {
                // 已取消
                otherOrderStatus = 7;
            }
            map.put("shopId",shopId);
            map.put("allOrderStatus",allOrderStatus);
            map.put("otherOrderStatus",otherOrderStatus);
            map.put("userName",userName);
            map.put("orderNum",orderNum);
            map.put("goodsName",goodsName);
            map.put("orderStartTime",orderStartTime);
            map.put("orderEndTime",orderEndTime);
            map.put("shopGateName",shopGateName);
            Page<OrderDetailsVO> page = new Page<>(Integer.parseInt(map.get("page") + ""),Integer.parseInt(map.get("limit") + ""));
            IPage<OrderDetailsVO> orderDetails = this.baseMapper.queryGateShopTakeOrderBase(page,map);
            for (int i = 0; i < orderDetails.getRecords().size(); i++) {
                String orderId = orderDetails.getRecords().get(i).getOrderId();
                // 退款状态
                Integer orderRefundStatus = orderDetails.getRecords().get(i).getOrderRefundStatus();
                // 退货状态
                Integer orderReturnStatus = orderDetails.getRecords().get(i).getOrderReturnStatus();
                // 订单状态
                Integer normalStatus = orderDetails.getRecords().get(i).getOrderStatus();
                // 涉及退款退货订单状态
                Integer Orderstatus = null;
                if (normalStatus == 3) {
                    // 未发货状态
                    if (orderRefundStatus == 1) {
                        // 未发货退款中
                        Orderstatus = 22;
                    } else if (orderRefundStatus == 2) {
                        // 商家拒绝或审核通过，继续发货，但不可再次申请退款
                        Orderstatus = 26;
                    } else if (orderRefundStatus == 0) {
                        Orderstatus = 3;
                    }
                } else if (normalStatus == 6) {
                    // 已完成状态
                    if (orderRefundStatus == 1) {
                        // 收货退款中
                        Orderstatus = 23;
                    } else if (orderRefundStatus == 2) {
                        Orderstatus = 25;
                    } else if (orderRefundStatus == 0 && orderReturnStatus == 0) {
                        Orderstatus = 6;
                    } else if (orderReturnStatus == 1) {
                        // 收货退货中
                        Orderstatus = 24;
                    } else if (orderReturnStatus == 2) {
                        Orderstatus = 25;
                    } else if (orderReturnStatus == 0 && orderRefundStatus == 0) {
                        Orderstatus = 6;
                    }
                } else {
                    Orderstatus = normalStatus;
                }
                // 存放最新状态
                orderDetails.getRecords().get(i).setOrderStatus(Orderstatus);
                List<GoodsDetailsVO> queryOrderDetails = this.baseMapper.queryOrders(orderId);
                if (queryOrderDetails == null) {
                    return ResponseResult.fail(2,"订单为空！");
                }
                orderDetails.getRecords().get(i).setGoodsDetails(queryOrderDetails);
            }
            return ResponseResult.success(PageUtils.getPage(orderDetails));
        } catch (Exception e) {
            log.info("SoldOrdersErrorResults:" + e.getMessage());
            return ResponseResult.fail(500,e.getMessage());
        }
    }

    @Override
    public ResponseResult queryCancelOrderDetails(Map<String, String> paramMap) {
        String token = (String) paramMap.get("token");
        String redeemCode = (String) paramMap.get("redeemCode");
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (!isExistToken) {
            return ResponseResult.fail(10086, "token失效，请重新获取！");
        }
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);

        Map<String, Object> stringObjectMap = this.baseMapper.queryCancelOrderDetails(redeemCode, ui.getUserId(), ui.getShopId());
        if (null == stringObjectMap) {
            return ResponseResult.fail(2, "抱歉，该核销码不是本店的！");
        }
        String periodOfValidity = (String) stringObjectMap.get("period_of_validity");
        boolean flag = false;
        if(null != periodOfValidity){
            DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                if(new Date().after(dateFormat.parse(periodOfValidity))){
                    flag = true;
                }
            }catch (Exception e){
                System.out.println(e.getMessage());
                log.error(e.getMessage());
            }
        }
        //是否核销  0是 1否 2已过期
        if (flag) {
            return ResponseResult.success(1, "订单过期",stringObjectMap);
        }else if (1 == (Long) stringObjectMap.get("is_cancel")) {
            return ResponseResult.success(1, "未核销",stringObjectMap);
        } else if (0 == (Long) stringObjectMap.get("is_cancel")) {
            return ResponseResult.success(1, "订单已核销",stringObjectMap);
        } else if (2 == (Long) stringObjectMap.get("is_cancel")) {
            return ResponseResult.success(1, "订单过期",stringObjectMap);
        }
        return ResponseResult.fail(500,"系统错误",stringObjectMap);

    }

    @Override
    public ResponseResult cancelOrder(Map<String, Object> map) {
        String token = (String) map.get("token");
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (!isExistToken) {
            return ResponseResult.fail(10086, "token失效，请重新获取！");
        }
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
        try {

            String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            String redeemCode = (String) map.get("redeemCode");
            OrderDetailsVO orderDetails = this.baseMapper.queryOrderDetails(redeemCode, ui.getShopId());
            if(null != orderDetails.getOrderRefundStatus() && 1 == orderDetails.getOrderRefundStatus()){
                return ResponseResult.success(1, "此订单退款中 无法核销！");
            }
            if(null != orderDetails.getOrderRefundStatus() && 2 == orderDetails.getOrderRefundStatus()){
                return ResponseResult.success(1, "此订单退款完成 无法核销！");
            }
            if (orderDetails.getIsCancel() == 0) {
                return ResponseResult.success(1, "此订单已经核销！");
            }
            Integer integer = this.baseMapper.updateOrderCancel(redeemCode, currentTime, orderDetails.getOrderId(), ui.getShopId());
            if (integer > 0) {
                return ResponseResult.success(1, "操作成功");
            }
            return ResponseResult.fail(2, "操作失败");
        } catch (Exception e) {
            log.info("JsonProcessingExceptionError:" + e.getMessage());
            return ResponseResult.fail(500, e.getMessage());
        }
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult businessCancelOrder(Map<String, Object> map) throws TransactionException {
        String token = (String) map.get("token");
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
        if (ui == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        try {

            String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            String redeemCode = (String) map.get("redeemCode");
            OrderBaseEntity orderDetails = this.baseMapper.selectOne(new LambdaQueryWrapper<OrderBaseEntity>()
                    .eq(OrderBaseEntity::getRedeemCode, redeemCode)
                    .eq(OrderBaseEntity::getShopId, ui.getShopId()));
            if (null != orderDetails && 2 == orderDetails.getIsCancel()) {
                //此订单退款中 无法核销！
                return ResponseResult.fail(BizCodeEnume.ORDER_EXPIRE_CANNOT_BE_CANCELLED);
            }
            if (null != orderDetails.getOrderRefundStatus() && CommonType.orderRefundStatus.REFUNDING.getCode().equals(orderDetails.getOrderRefundStatus())) {
                //此订单退款中 无法核销！
                return ResponseResult.fail(BizCodeEnume.ORDER_REFUND_CANNOT_BE_CANCELLED);
            }
            if (null != orderDetails.getOrderRefundStatus() && CommonType.orderRefundStatus.REFUND_COMPLETED.getCode().equals(orderDetails.getOrderRefundStatus())) {
                //此订单退款完成 无法核销！
                return ResponseResult.fail(BizCodeEnume.ORDER_REFUND_COMPLETED);
            }
            if (orderDetails.getIsCancel() == 0) {
                //此订单已经核销！
                return ResponseResult.fail(CommonType.isCancel.NO.getDesc());
            }

            Integer integer = this.baseMapper.update(null, new LambdaUpdateWrapper<OrderBaseEntity>()
                    .eq(OrderBaseEntity::getRedeemCode, redeemCode)
                    .eq(OrderBaseEntity::getShopId, ui.getShopId())
                    .eq(OrderBaseEntity::getOrderId, orderDetails.getOrderId())
                    .set(OrderBaseEntity::getOrderStatus, CommonType.orderStatus.CONFIRM_RECEIPT.getCode())
                    .set(OrderBaseEntity::getCancelDate, currentTime)
                    .set(OrderBaseEntity::getIsCancel, CommonType.isCancel.NO.getCode())
                    .set(OrderBaseEntity::getOrderFinishedTime, LocalDateTime.now())
                    .set(OrderBaseEntity::getOrderLastReturnTime, LocalDateTime.now()));
            if (integer > 0) {
                //核销成功增加积分----查询积分规则
                ResponseResult resultResp = baseServiceClient.queryIntegralRules();
                Map<String, Integer> integralRules = (Map<String, Integer>) resultResp.getData();
                //修改会员积分和会员等级
                MemberMessageListIntegralDTO updateMemberMessageListIntegral = new MemberMessageListIntegralDTO();
                BigDecimal jifen = orderDetails.getOrderPaymentAmount().multiply(new BigDecimal(integralRules.get("ruleConsume")));
                long l = jifen.setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
                ArrayList<String> list = new ArrayList<>();
                //当前逻辑存在问题，需要将积分加到员工账号上
//                    if (ui.getIsEmployee() == 1) {
//                        //当是员工账号是积分归属企业主账号
//                        userId = userServiceClient.getPrimaryAccountId(userId);
//                    }
                list.add(orderDetails.getBuyerUserId());
                updateMemberMessageListIntegral.setUserIdList(list);
                updateMemberMessageListIntegral.setIntegral((int) l);
                //1是增加积分 0 是扣除积分
                updateMemberMessageListIntegral.setType(CommonType.commonStatus.YES.getCode());
                userServiceClient.updateMemberIntegral(updateMemberMessageListIntegral);
                //添加积分修改记录
                Map<String, Object> pointParam = new HashMap<>();
                pointParam.put("PointsLogType", CommonType.pointsLogType.GAIN.getCode());
                pointParam.put("ClassId", CommonType.pointType.PURCHASE.getCode());
                pointParam.put("PointsLogTime", DateUtils.getTime());
                pointParam.put("PointsLogDesc", CommonType.pointType.PURCHASE.getDesc());
                pointParam.put("PointsLogFlag", "reg");
                pointParam.put("UserId", orderDetails.getBuyerUserId());
                pointParam.put("orderId", orderDetails.getOrderId());
                pointParam.put("PointsLogPoints", (int) l);
                pointParam.put("PointsLogOperate", CommonType.pointType.PURCHASE.getDesc());
                pointParam.put("proportion", integralRules.get("ruleConsume"));
                userServiceClient.insertPointLogByMap(pointParam);
                return ResponseResult.success();
            } else {
                return ResponseResult.fail();
            }
        } catch (Exception e) {
            log.info("Exception:" + e.getMessage());
            // 回滚
            GlobalTransactionContext.reload(RootContext.getXID()).rollback();
            return ResponseResult.fail(e.getMessage());
        }
    }

    @Override
    public ResponseResult dealerDetailList(Map<String, String> map) {
        String token = map.get("token");
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (!isExistToken) {
            return ResponseResult.fail(10086, "token失效，请重新获取！");
        }
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
        try {
            String shopId = ui.getShopId();
            String orderNum = StringUtils.isEmpty(map.get("orderNum")) ? null : "'" + map.get("orderNum") + "'";

            String goodsName = StringUtils.isEmpty(map.get("goodsName")) ? null : "'" + map.get("goodsName") + "'";

            String orderStartTime = StringUtils.isEmpty(map.get("orderStartTime")) ? null : "'" + map.get("orderStartTime") + "'";
            String orderEndTime = StringUtils.isEmpty(map.get("orderEndTime")) ? null : "'" + map.get("orderEndTime") + "'";
            String allOrderStatus = null;
            Integer otherOrderStatus = 6;
            Integer dropShipping = 1;
            String deliverShopName = StringUtils.isEmpty(map.get("deliverShopName")) ? null : "'" + map.get("deliverShopName") + "'";
            Map<String,Object> paraMap = new HashMap<>();
            paraMap.put("shopId",shopId);
            paraMap.put("allOrderStatus",allOrderStatus);
            paraMap.put("otherOrderStatus",otherOrderStatus);
            paraMap.put("orderNum",orderNum);
            paraMap.put("goodsName",goodsName);
            paraMap.put("orderStartTime",orderStartTime);
            paraMap.put("orderEndTime",orderEndTime);
            paraMap.put("orderType",CommonType.orderType.GOODS_TYPE.getCode());
            paraMap.put("dropShipping",dropShipping);
            paraMap.put("orderSource",2);
            paraMap.put("deliverShopName",deliverShopName);
            Page<DealerOrderDetailVO> page = new Page<>(Integer.parseInt(map.get("page")),Integer.parseInt(map.get("limit")));
            IPage<DealerOrderDetailVO> orderDetails = this.baseMapper.queryDealerOrderBase(page,paraMap);
            return ResponseResult.success(PageUtils.getPage(orderDetails));
        } catch (Exception e) {
            log.info("SoldOrdersErrorResults:" + e.getMessage());
            return ResponseResult.fail(500, e.getMessage());
        }
    }

    @Override
    public ResponseResult changeShipments(Map<Object, Object> map) {
        String token = (String) map.get("token");
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (!isExistToken) {
            return ResponseResult.fail(10086, "token失效，请重新获取！");
        }
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
        String orderId = (String) map.get("orderId");
        // 物流单号
        String orderShippingCode = (String) map.get("orderShippingCode");
        // 配送公司ID
        Integer orderShippingExpressId = (Integer) map.get("orderShippingExpressId");
        boolean isChangeShipmentsByBaseSuccess = false;
        boolean isChangeShipmentsByGoodsSuccess = false;
        // 物流发货备注
        String orderShippingMessage = (String) map.get("orderShippingMessage");
        if (orderShippingExpressId == null) {
            isChangeShipmentsByBaseSuccess = this.baseMapper.updateChangeShipmentsByBase(orderId, orderShippingCode, orderShippingMessage);
            isChangeShipmentsByGoodsSuccess = this.baseMapper.updateChangeShipmentsByGoods(orderId, orderShippingCode, orderShippingMessage);
        } else {
            if (orderShippingExpressId == 47) {
                String receiverPhone = this.baseMapper.queryReceiverPhone(orderId);
                // 获取手机号后四位
                String phoneNumber = receiverPhone.substring(7, 11);
                // 顺丰快递物流号
                orderShippingCode = orderShippingCode + ":" + phoneNumber;
            }
            isChangeShipmentsByBaseSuccess = this.baseMapper.updateChangeAllShipmentsByBase(orderId, orderShippingExpressId, orderShippingCode,
                    orderShippingMessage);
            isChangeShipmentsByGoodsSuccess = this.baseMapper.updateChangeAllShipmentsByGoods(orderId, orderShippingExpressId, orderShippingCode,
                    orderShippingMessage);
        }
        if (isChangeShipmentsByBaseSuccess && isChangeShipmentsByGoodsSuccess) {
            return ResponseResult.success(1, "更改成功！");
        }
        return ResponseResult.fail(2, "更改失败！");
    }

    @Override
    public ResponseResult queryMemberOrderDetail(Map<String, Object> param) {
        Integer returnFlag = 0;
        String token = (String) param.get("token");
        if (RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token)) {
            IPage<UserInfoOrderDetailVO> page=this.baseMapper.queryUserorderInfoList(new Query<UserInfoOrderDetailVO>().getPage(param),
                    param);

            for(UserInfoOrderDetailVO r:page.getRecords()) {
                String orderId = r.getOrderId();
                OrderBaseEntity orderInfoEntity = this.baseMapper.selectById(orderId);
                Integer virtualGoods = orderInfoEntity.getVirtualGoods();
                Integer orderIsShopTake = orderInfoEntity.getOrderIsShopTake();
                if( null != orderIsShopTake && 1 == orderIsShopTake){
                    r.setOrderType(3);
                }else{
                    if(null != virtualGoods && 0 == virtualGoods){
                        r.setOrderType(2);
                        r.setPastDue(orderInfoEntity.getPastDue());
                        r.setIsCancel(orderInfoEntity.getIsCancel());
                    }else{
                        r.setOrderType(1);
                    }
                }
                int returnStatus = Integer.valueOf(orderInfoEntity.getOrderReturnStatus());
                int refundStatus =  Integer.valueOf(orderInfoEntity.getOrderRefundStatus());
                r.setReturnStatus(returnStatus);
                r.setRefundStatus(refundStatus);
                if (2 == returnStatus || 2 == refundStatus) {
                    BigDecimal returnAmount = new BigDecimal(orderInfoEntity.getOrderRefundAmount());
                    BigDecimal orderAmount = orderInfoEntity.getOrderPaymentAmount();
                    if (orderAmount.compareTo(returnAmount) > 0) {
                        returnFlag = 2;
                    } else if ((orderAmount.compareTo(returnAmount) == 0)) {
                        returnFlag = 1;
                    }
                }
                r.setReturnFlag(returnFlag);
            }


            return ResponseResult.success(PageUtils.getPage(page));
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
    }

    @Override
    public ResponseResult separateShipments(ShipmentsDTO param) throws TransactionException {
        String token = param.getToken();
        ResponseResult rr = ParseTokenUtils.getShopUserInfo(token);
        if (rr.getCode() != CommonStatusEnum.SUCCESS.getCode()) {
            return rr;
        }
        String orderId = param.getOrderId();
        // 查询订单信息 如状态，退货退款状态，收货人手机号
        OrderBaseEntity obe = this.baseMapper.selectOne(new LambdaQueryWrapper<OrderBaseEntity>()
                .eq(OrderBaseEntity::getOrderId, orderId));
        String receiverPhone = obe.getOrderReceiverContact();
        if (obe.getOrderStatus() == 3 && obe.getOrderRefundStatus().equals("1")) {
            return ResponseResult.fail(BizCodeEnume.ORDER_AFTER_SALES.getCode(), BizCodeEnume.ORDER_AFTER_SALES.getMsg());
        } else if (obe.getOrderStatus() == 6 && obe.getOrderRefundStatus().equals("2")) {
            return ResponseResult.fail(BizCodeEnume.ORDER_AFTER_SALES_COMPLETION.getCode(), BizCodeEnume.ORDER_AFTER_SALES_COMPLETION.getMsg());
        }
        List<ShipmentsGoodsDTO> spList = param.getGoodsDetails();
        if (spList.size() == 1) {
            Map<Object, Object> map = new HashMap<Object, Object>();
            map.put("token", token);
            map.put("orderId", orderId);
            map.put("shippingAddressId", spList.get(0).getShippingAddressId());
            map.put("orderSellerName", spList.get(0).getOrderSellerName());
            map.put("orderSellerAddress", spList.get(0).getOrderSellerAddress());
            map.put("orderSellerContact", spList.get(0).getOrderSellerContact());
            map.put("orderShippingExpressId", spList.get(0).getOrderShippingExpressId());
            map.put("orderShippingCode", spList.get(0).getOrderShippingCode());
            map.put("orderShippingMessage", spList.get(0).getOrderShippingMessage());
            shipments(map);
        }
        // 配送时间
        String orderShippingTime = DateUtils.getTime();
        StringBuilder sb = new StringBuilder();
        boolean isUpdateSuccessByOrderGoods = false;
        Integer orderStatus = 4;
        String orderSellerName = null;
        String orderSellerAddress = null;
        String orderSellerContact = null;
        Integer orderShippingExpressId = null;
        String orderShippingMessage = null;
        Integer shippingAddressId = null;
        String orderShippingCode = null;
        // 商品订单是否已经发货。1-是，0-否，默认0(orderGoods)
        Integer orderGoodsIdDeliver = 1;
        for (ShipmentsGoodsDTO shipmentsGoodsPara : spList) {
            if ("".equals(shipmentsGoodsPara.getOrderShippingCode().trim())) {
                return ResponseResult.fail(BizCodeEnume.SHOPPING_CODE_IS_NULL);
            }
            // 商品id
            Integer goodsId = shipmentsGoodsPara.getGoodsId();
            // 商家发货地址id
            shippingAddressId = shipmentsGoodsPara.getShippingAddressId();
            // 发货人姓名
            orderSellerName = shipmentsGoodsPara.getOrderSellerName();
            // 发货人地址
            orderSellerAddress = shipmentsGoodsPara.getOrderSellerAddress();
            // 发货人联系方式
            orderSellerContact = shipmentsGoodsPara.getOrderSellerContact();
            // 配送公司ID
            orderShippingExpressId = shipmentsGoodsPara.getOrderShippingExpressId();
            // 物流发货备注
            orderShippingMessage = shipmentsGoodsPara.getOrderShippingMessage();
            // 物流单号
            orderShippingCode = shipmentsGoodsPara.getOrderShippingCode();
            sb.append(shipmentsGoodsPara.getOrderShippingCode()).append(",");

            if (orderShippingExpressId == 47) {
                // 获取手机号后四位
                String phoneNumber = receiverPhone.substring(7, 11);
                // 顺丰快递物流号
                orderShippingCode = orderShippingCode + ":" + phoneNumber;
            }
            Map<String, Object> mapGoods = new HashMap<>();
            mapGoods.put("orderId", orderId);
            mapGoods.put("goodsId", goodsId);
            mapGoods.put("orderStatus", orderStatus);
            mapGoods.put("orderGoodsIdDeliver", orderGoodsIdDeliver);
            mapGoods.put("orderSellerName", orderSellerName);
            mapGoods.put("orderSellerAddress", orderSellerAddress);
            mapGoods.put("orderSellerContact", orderSellerContact);
            mapGoods.put("orderShippingTime", orderShippingTime);
            mapGoods.put("orderShippingExpressId", orderShippingExpressId);
            mapGoods.put("orderShippingCode", orderShippingCode);
            mapGoods.put("orderShippingMessage", orderShippingMessage);
            //发货 order_goods
            isUpdateSuccessByOrderGoods = orderGoodsMapper.updateSeparateShipmentsByOrderGoods(mapGoods);
        }
        Integer lastNum = sb.toString().lastIndexOf(",");
        String allShippingCode = (sb).substring(0, lastNum);
        Map<String, Object> mapBase = new HashMap<>();
        mapBase.put("orderId", orderId);
        mapBase.put("orderStatus", orderStatus);
        mapBase.put("orderSellerName", orderSellerName);
        mapBase.put("orderSellerAddress", orderSellerAddress);
        mapBase.put("orderSellerContact", orderSellerContact);
        mapBase.put("orderShippingTime", orderShippingTime);
        mapBase.put("orderShippingExpressId", orderShippingExpressId);
        mapBase.put("allShippingCode", allShippingCode);
        mapBase.put("orderShippingMessage", orderShippingMessage);
        //更改 order_base
        boolean isUpdateSuccessByOrderBase = this.baseMapper.updateSeparateShipmentsByOrderBase(mapBase);
        if (isUpdateSuccessByOrderGoods && isUpdateSuccessByOrderBase) {
            payMentServiceClient.changeConsumeRecord(orderId);
            UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
            this.baseMapper.updateOrderMessageProcessingStatus(ui.getShopId(),orderId);
            //获取店铺名称
            String shopName = obe.getShopName();

            //发送站内信通知
            PlatformMessageVO platformMessage = new PlatformMessageVO();
            platformMessage.setCreateTime(new Date());
            platformMessage.setUserId(obe.getBuyerUserId());//买家id
            platformMessage.setMessageUserName(obe.getBuyerUserName());
            platformMessage.setMessageContent("你的订单" + orderId + "已发货");
            platformMessage.setMessageTitle("订单发货提醒");
            platformMessage.setCreater(shopName);
            this.baseMapper.insertMessage(platformMessage);

            return ResponseResult.success();
        }
        return ResponseResult.fail(BizCodeEnume.UPDATE_ERROR);
    }

    @Override
    public ResponseResult updateAddressInformation(Map<Object, Object> map) {
        String token = map.get("token").toString();
        ResponseResult rr = ParseTokenUtils.getShopUserInfo(token);
        if (rr.getCode() != CommonStatusEnum.SUCCESS.getCode()) {
            return rr;
        }
        String orderId = (String) map.get("orderId");
        String orderReceiverName = (String) map.get("orderReceiverName");
        String orderReceiverAddress = (String) map.get("orderReceiverAddress");
        String orderReceiverContact = (String) map.get("orderReceiverContact");
        Map<String, Object> mapInfo = new HashMap<>();
        mapInfo.put("orderId", orderId);
        mapInfo.put("orderReceiverName", orderReceiverName);
        mapInfo.put("orderReceiverAddress", orderReceiverAddress);
        mapInfo.put("orderReceiverContact", orderReceiverContact);
        boolean changeAddressInformation = this.baseMapper.updateAddressInformation(mapInfo);
        if (changeAddressInformation) {
            return ResponseResult.success(BizCodeEnume.UPDATE_SUCCEEDED);
        }
        return ResponseResult.fail(BizCodeEnume.UPDATE_ERROR);
    }

    @Override
    public ResponseResult queryAddressInformation(Map<Object, Object> map) {
        String orderId = (String) map.get("orderId");
        OrderBaseEntity entity = this.baseMapper.selectById(orderId);
        if (entity != null) {
            return ResponseResult.success(entity);
        }
        return ResponseResult.fail(BizCodeEnume.ORDER_IS_NULL.getCode(), BizCodeEnume.ORDER_IS_NULL.getMsg());
    }

    @Override
    public ResponseResult importShipmentsOrderExport(MultipartFile file) throws TransactionException {
        // 解析excel数据
        List<Map<Object, Object>> mapList = ExcelsUtil.readExcel(file);
        if (!mapList.isEmpty()) {
            int count = 0;
            StringBuilder desc = new StringBuilder();
            for (Map<Object, Object> map : mapList) {
                if (null == map.get("shippingAddressId") || "".equals(map.get("shippingAddressId").toString())) {
                    TransactionManagerHolder.get().rollback(RootContext.getXID());
                    return ResponseResult.fail(BizCodeEnume.SHIPPING_ADDRESS_IS_NULL);
                }
                if (null == map.get("orderSellerName") || "".equals(map.get("orderSellerName").toString())) {
                    TransactionManagerHolder.get().rollback(RootContext.getXID());
                    return ResponseResult.fail(BizCodeEnume.CONSIGNOR_NAME_IS_NULL);
                }
                if (null == map.get("orderSellerAddress") || "".equals(map.get("orderSellerAddress").toString())) {
                    TransactionManagerHolder.get().rollback(RootContext.getXID());
                    return ResponseResult.fail(BizCodeEnume.CONSIGNOR_ADDRESS_IS_NULL);
                }
                if (null == map.get("orderSellerContact") || "".equals(map.get("orderSellerContact").toString())) {
                    TransactionManagerHolder.get().rollback(RootContext.getXID());
                    return ResponseResult.fail(BizCodeEnume.CONSIGNOR_TEL_IS_NULL);
                }
                if (null == map.get("orderShippingExpressId") || "".equals(map.get("orderShippingExpressId").toString())) {
                    TransactionManagerHolder.get().rollback(RootContext.getXID());
                    return ResponseResult.fail(BizCodeEnume.EXPRESS_ID_IS_NULL);
                }
                if (null == map.get("goodsId") || "".equals(map.get("goodsId").toString())) {
                    TransactionManagerHolder.get().rollback(RootContext.getXID());
                    return ResponseResult.fail(BizCodeEnume.GOODS_ID_IS_NULL);
                }
                if (null == map.get("orderShippingCode") || "".equals(map.get("orderShippingCode").toString())) {
                    TransactionManagerHolder.get().rollback(RootContext.getXID());
                    return ResponseResult.fail(BizCodeEnume.ORDER_AFTER_SALES_COMPLETION);
                }
                ResponseResult resp = piLiangFahuoShipments(map, CommonType.commonStatus.YES.getCode());
                if (CommonStatusEnum.SUCCESS.getCode() == resp.getCode()) {
                    count++;
                } else {
                    desc.append(" ").append(map.get("orderId"));
                }
            }
            return ResponseResult.success("发货成功" + count + ",发货失败的订单" + desc);
        }
        return ResponseResult.fail(2, "excel文件错误");
    }

    @Override
    public ResponseResult batchShipmentsOrderExport(Map<String, Object> map, HttpServletResponse response) {
        String token = map.get("token").toString();
        ArrayList orderIds = (ArrayList) map.get("OrderIds");
        UserInfoVO userInfoVO = ParseTokenUtils.getUserInfoByToken(token);
        if (userInfoVO == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
        Integer id = 1;
        try {
            //批量 获取选中的orderIds  获取订单信息 下载表格
            List<ShipmentsOrderDetailDTO> orderList = this.baseMapper.batchShipmentsOrderExport(orderIds);
            String[] title = {"ID", "订单号", "订单创建时间", "支付单号", "支付方式", "支付时间", "配送公司ID", "配送公司名字", "物流单号",
                    "收货人姓名", "收货人详细地址", "收货人联系方式", "订单应付金额", "商品Id", "商品名称", "商品数量", "商品单价", "发货人名称", "发货人地址", "发货人手机号", "发货地址id"};
            List<Map<String, String>> list = Lists.newArrayList();
            for (int i = 0; i < orderList.size(); i++) {
                Integer paymentCode = orderList.get(i).getPaymentCode();
                String paymentCodeName = null;
                if (paymentCode == 1) {
                    paymentCodeName = "余额支付";
                } else if (paymentCode == 2) {
                    paymentCodeName = "支付宝支付";
                } else if (paymentCode == 3) {
                    paymentCodeName = "微信支付";
                } else if (paymentCode == 4) {
                    paymentCodeName = "通联支付";
                } else if (paymentCode == 5) {
                    paymentCodeName = "健康账户余额支付";
                } else if (paymentCode == 6) {
                    paymentCodeName = "购物卡支付";
                } else if (paymentCode == 7) {
                    paymentCodeName = "充值卡+支付宝";
                } else if (paymentCode == 8) {
                    paymentCodeName = "充值卡+微信";
                } else if (paymentCode == 9) {
                    paymentCodeName = "蜂币支付";
                } else if (paymentCode == 10) {
                    paymentCodeName = "蜂币+支付宝";
                } else if (paymentCode == 11) {
                    paymentCodeName = "蜂币+微信";
                } else if (paymentCode == 12) {
                    paymentCodeName = "线下支付（上传凭证)";
                } else {
                    paymentCodeName = "未知";
                }
                orderList.get(i).setPaymentCodeName(paymentCodeName);

                HashMap<String, String> mPut = Maps.newHashMap();
                mPut.put("ID", String.valueOf(id));
                mPut.put("订单号", orderList.get(i).getOrderId());
                mPut.put("订单创建时间", orderList.get(i).getOrderCreateTime());
                mPut.put("支付单号", orderList.get(i).getPaymentNumber());
                mPut.put("支付方式", orderList.get(i).getPaymentCodeName());
                mPut.put("支付时间", orderList.get(i).getPaymentTime());
                mPut.put("配送公司ID", map.get("expressId").toString());
                mPut.put("配送公司名字", map.get("expressName").toString());
                mPut.put("物流单号", null);
                mPut.put("收货人姓名", orderList.get(i).getOrderReceiverName());
                mPut.put("收货人详细地址", orderList.get(i).getOrderReceiverAddress());
                mPut.put("收货人联系方式", orderList.get(i).getOrderReceiverContact());
                mPut.put("订单应付金额", orderList.get(i).getOrderPaymentAmount().toString());
                mPut.put("商品Id", orderList.get(i).getGoodsId().toString());
                mPut.put("商品名称", orderList.get(i).getGoodsName());
                mPut.put("商品数量", orderList.get(i).getOrderGoodsNum().toString());
                mPut.put("商品单价", orderList.get(i).getGoodsPrice().toString());
                mPut.put("发货人名称", map.get("orderSellerName").toString());
                mPut.put("发货人地址", map.get("orderSellerAddress").toString());
                mPut.put("发货人手机号", map.get("orderSellerContact").toString());
                mPut.put("发货地址id", map.get("shippingAddressId").toString());

                list.add(mPut);
                id++;
            }
            /* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 *//* 此处key对应每一列的标题 */
            Map<String, List<Map<String, String>>> m = Maps.newHashMap();
            m.put("待发货订单数据", list);
            String url = ExcelsUtil.createExcel(title, m, new int[]{0});/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */
            return ResponseResult.success(url);
        } catch (Exception e) {
            log.info("orderExportErrorResults:" + e.getMessage());
            return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED.getCode(), BizCodeEnume.OPERATION_FAILED.getMsg());
        }
    }

    @Override
    public ResponseResult queryUnshippedOrder(RetrunQueryPrintDTO param) {
        UserInfoVO userInfoVO = ParseTokenUtils.getUserInfoByToken(param.getToken());

        //根据店铺查询 未发货的订单
        Page<ManageOrderbaseListVO> page = new Page<>(param.getPage(), param.getLimit());
        IPage<ManageOrderbaseListVO> list = this.baseMapper.selectOrderbaseByShopIdParam(page, param);
        return ResponseResult.success(PageUtils.getPage(list));
    }

    @Override
    public ResponseResult shippingOrderExport(Map<String, Object> map, HttpServletResponse response) {
        String token = map.get("token").toString();
        ResponseResult rr = ParseTokenUtils.getShopUserInfo(token);
        if (rr.getCode() != CommonStatusEnum.SUCCESS.getCode()) {
            return rr;
        }
        UserInfoVO ui = JSON.parseObject(JSON.toJSONString(rr.getData()), UserInfoVO.class);
        String shopId = ui.getShopId();
        // 买家
        String userName = (String) map.get("userName");
        // 订单号
        String orderNum = (String) map.get("orderNum");
        // 下单开始时间
        String orderStartTime = (String) map.get("orderStartTime");
        // 下单结束时间
        String orderEndTime = (String) map.get("orderEndTime");
        // 发货状态
        Integer status = Integer.parseInt(map.get("status").toString());
        Map<String, Object> mapExport = new HashMap<>();
        mapExport.put("shopId", shopId);
        mapExport.put("status", status);
        mapExport.put("userName", userName);
        mapExport.put("orderNum", orderNum);
        mapExport.put("orderStartTime", orderStartTime);
        mapExport.put("orderEndTime", orderEndTime);
        List<SoldOrderExportDTO> orderList = this.baseMapper.queryShippingExportParams(mapExport);
        String[] title = {"订单号", "买家昵称", "收件人姓名", "手机", "电话", "省", "市", "区", "地址", "邮编", "运费", "实付款", "商品名称",
                "商家编码", "销售属性", "单价", "数量", "优惠", "下单时间", "付款时间", "买家留言", "卖家备注"};
        List<Map<String, String>> list = Lists.newArrayList();
        for (SoldOrderExportDTO soldOrderExportPara : orderList) {
            Integer orderStatus = soldOrderExportPara.getOrderStatus();
            String statusName = null;
            if (orderStatus == 1) {
                statusName = "待付款";
            } else if (orderStatus == 2) {
                statusName = "待配货";
            } else if (orderStatus == 3) {
                statusName = "待发货";
            } else if (orderStatus == 4) {
                statusName = "已发货";
            } else if (orderStatus == 5) {
                statusName = "已签收";
            } else if (orderStatus == 6) {
                statusName = "已完成";
            } else if (orderStatus == 7) {
                statusName = "已取消";
            } else if (orderStatus == 8) {
                statusName = "退款中";
            } else if (orderStatus == 9) {
                statusName = "退款完成";
            }
            soldOrderExportPara.setOrderStatusName(statusName);
            HashMap<String, String> mPut = Maps.newHashMap();
            mPut.put("订单号", soldOrderExportPara.getOrderId());
            mPut.put("买家昵称", soldOrderExportPara.getBuyerUserName());
            mPut.put("收件人姓名", soldOrderExportPara.getOrderReceiverName());
            mPut.put("手机", soldOrderExportPara.getOrderReceiverContact());
            mPut.put("电话", null);
            mPut.put("省", soldOrderExportPara.getProvince());
            mPut.put("市", soldOrderExportPara.getCity());
            mPut.put("区", soldOrderExportPara.getArea());
            mPut.put("地址", soldOrderExportPara.getOrderReceiverAddress());
            mPut.put("邮编", null);

            mPut.put("运费", soldOrderExportPara.getOrderShippingFee().toString());
            mPut.put("实付款", soldOrderExportPara.getOrderPaymentAmount().toString());
            mPut.put("商品名称", soldOrderExportPara.getGoodsName());
            mPut.put("商家编码", soldOrderExportPara.getShopId());
            mPut.put("销售属性", soldOrderExportPara.getOrderSpecChineseValue());
            mPut.put("单价", soldOrderExportPara.getGoodsPrice().toString());
            mPut.put("数量", soldOrderExportPara.getOrderGoodsNum().toString());
            mPut.put("优惠", soldOrderExportPara.getOrderDiscountFee().toString());

            mPut.put("下单时间", soldOrderExportPara.getOrderCreateTime());
            mPut.put("付款时间", soldOrderExportPara.getPaymentTime());
            mPut.put("买家留言", soldOrderExportPara.getOrderMessage());
            mPut.put("卖家备注", soldOrderExportPara.getOrderSellerMessage());
            list.add(mPut);
        }
        /* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 *//* 此处key对应每一列的标题 */
        Map<String, List<Map<String, String>>> m = Maps.newHashMap();
        m.put("测试合并数据", list);
        String url = ExcelsUtil.createExcel(title, m, new int[]{0});/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */
        return ResponseResult.success(url);
    }

    @Override
    public ResponseResult queryRecycleBin(Map<String, Object> map) {
        String token = (String) map.get("token");
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (!isExistToken) {
            return ResponseResult.fail(10086, "token失效，请重新获取！");
        }
        try {
            String orderId = (String) map.get("orderId");
            if (orderId == null || orderId == "") {
                return ResponseResult.fail(2, "orderId不能为null");
            }
            List<GoodsDetailsVO> goodsDetails = this.baseMapper.queryRecycleBin(orderId);
            return ResponseResult.success(goodsDetails);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(500,e.getMessage());
        }
    }

    @Override
    public ResponseResult queryLogisticsMessage(Map<String, Object> map) {
        String token = (String) map.get("token");
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (!isExistToken) {
            return ResponseResult.fail(10086, "token失效，请重新获取！");
        }
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
        if (null == ui.getShopId()) {
            return ResponseResult.fail(10086, "没有权限");
        }

        String orderId = (String) map.get("orderId");
        List<LogisticsMessageVO> shippingList = this.baseMapper.queryLogisticsMessage(orderId);
        for (int i = 0; i < shippingList.size(); i++) {
            String expCode = shippingList.get(i).getOrderShippingCode();
            List<ShippingGoodsMessageVO> sgm = this.baseMapper.queryGoodsMessage(expCode, orderId);
            Integer expId = shippingList.get(i).getOrderShippingExpressId();
            // 查询物流名称
            String expName = this.baseMapper.queryExpressNameById(expId);
            shippingList.get(i).setShippingName(expName);
            shippingList.get(i).setGoodsMessage(sgm);
        }
        return ResponseResult.success(shippingList);
    }

    @Override
    public ResponseResult remindPay(Map<String, Object> map) {
        String token = (String) map.get("token");
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (!isExistToken) {
            return ResponseResult.fail(10086, "token失效，请重新获取！");
        }
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
        if (null == ui.getShopId()) {
            return ResponseResult.fail(10086, "没有权限");
        }

        String orderId = (String) map.get("orderId");
        Map<String,String> maps = this.baseMapper.queryUserPhone2(orderId);
        //商家端发货成功提醒短信
        thirdPartyServiceClient.goodsObligation(maps);
        //发送站内信通知
        PlatformMessageVO platformMessage = new PlatformMessageVO();
        platformMessage.setCreateTime(new Date());
        platformMessage.setUserId(maps.get("buyerUserId"));//买家id
        platformMessage.setMessageUserName(maps.get("buyer_user_name"));
        platformMessage.setMessageContent("待支付提醒：您刚购买的商品订单" + orderId + "未支付成功，订单即将取消，请尽快支付~");
        platformMessage.setMessageTitle("待支付提醒");
        platformMessage.setCreater(String.valueOf(maps.get("shopName")));
        this.baseMapper.insertMessage(platformMessage);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult shipmentsOrder(Map<String, Object> map) {
        String token = map.get("token").toString();
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
        if (ui==null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }

        String Seller_Trade_Deliver = "Seller_Trade_Deliver";
        Integer shopId = Integer.valueOf(ui.getShopId());
        if (containLimits(ui, Seller_Trade_Deliver)) {
            // 买家
            String userName = (String) map.get("userName");
            // 订单号
            String orderNum = (String) map.get("orderNum");
            // 下单开始时间
            String orderStartTime = (String) map.get("orderStartTime")==""?null:(String) map.get("orderStartTime");
            // 下单结束时间
            String orderEndTime = (String) map.get("orderEndTime")==""?null:(String) map.get("orderEndTime");
            // 发货状态
            Integer status = Integer.parseInt(map.get("status") + "");
            String allOrderStatus = null;
            Integer otherOrderStatus = null;
            if (status == 1) {
                allOrderStatus = "1";
            }else{
                otherOrderStatus = status;
            }
            Integer currentPage = Integer.parseInt(map.get("page") + "");
            Integer pageSize = Integer.parseInt(map.get("limit") + "");
            String plusOrder = String.valueOf(map.get("plusOrder"));
            Page<ShipmentsByOrderBaseVO> page = new Page<>(currentPage, pageSize);
            Map<String, Object> mapBase = new HashMap<>();
            mapBase.put("shopId", shopId);
            mapBase.put("allOrderStatus", allOrderStatus);
            mapBase.put("otherOrderStatus", otherOrderStatus);
            mapBase.put("userName", userName);
            mapBase.put("orderNum", orderNum);
            mapBase.put("orderStartTime", orderStartTime);
            mapBase.put("orderEndTime", orderEndTime);
            mapBase.put("orderSource", 2);
            mapBase.put("plusOrder", plusOrder);
            IPage<ShipmentsByOrderBaseVO> orderBaseIPage = this.baseMapper.queryShipmentsOrderBase(page, mapBase);
            List<ShipmentsByOrderBaseVO> orderDetails = orderBaseIPage.getRecords();
            //设置待发货订单的信息
            boolean flag = setShippedOrderDetails(orderDetails);
            if (flag) {
                return ResponseResult.success(PageUtils.getPage(orderBaseIPage));
            }
            return ResponseResult.fail(BizCodeEnume.ORDER_IS_NULL.getCode(), BizCodeEnume.ORDER_IS_NULL.getMsg());
        }
        return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);


    }

    @Override
    public ResponseResult reduction(Map<String, Object> map) {
        UserInfoVO userInfoVO = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());
        if (userInfoVO == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        String orderId = (String) map.get("orderId");
        boolean isSuccess = this.baseMapper.updateShopHidden(CommonType.commonStatus.NO.getCode(), orderId);
        if (isSuccess) {
            return ResponseResult.success();
        }
        return ResponseResult.fail(BizCodeEnume.UPDATE_ERROR);
    }

    @Override
    public ResponseResult queryRecycleBinPageDetails(Map<String, Object> map) {
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());
        if (ui == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
        }
        PageInfo pi = new PageInfo();
        Integer shopId = Integer.valueOf(ui.getShopId());
        //条件参数
        map.put("shopId", shopId);
        String allOrderStatus = null;
        Integer otherOrderStatus = null;
//        Integer status = Integer.parseInt(map.get("status") + "");
//
//        map.put("allOrderStatus", allOrderStatus);
//        map.put("otherOrderStatus", status);
        IPage<OrderDetailsVO> page = this.baseMapper.queryRecycleBinByOrderBase(new Query<OrderDetailsVO>().getPage(map), map);

        for (int i = 0; i < page.getRecords().size(); i++) {
            String orderId = page.getRecords().get(i).getOrderId();
            List<GoodsDetailsVO> queryOrderDetails = orderGoodsMapper.queryOrders(orderId);
            if (queryOrderDetails != null) {
                page.getRecords().get(i).setGoodsDetails(queryOrderDetails);
            } else {
                return ResponseResult.fail(BizCodeEnume.ORDER_IS_NULL.getCode(), BizCodeEnume.ORDER_IS_NULL.getMsg());
            }
        }
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult recycleBinExcel(Map<String, Object> map) {
        String token = (String) map.get("token");
        boolean isExist = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (isExist) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
                String shopId =ui.getShopId();
                if(null == shopId){
                    return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
                }
                String Seller_Trade_Order = "Seller_Trade_Order";
                if (containLimits(ui, Seller_Trade_Order)) {
                    String username = (String) map.get("userName");
                    String userName = null;
                    if (username == "") {
                        userName = "";
                    } else {
                        userName = "'" + username + "'";
                    }

                    Integer virtualGoods = (Integer) map.get("virtualGoods");
                    String ordernum = (String) map.get("orderNum");
                    String orderNum = null;
                    if (ordernum == "") {
                        orderNum = "";
                    } else {
                        orderNum = "'" + ordernum + "'";
                    }
                    String goodsname = (String) map.get("goodsName");
                    String goodsName = null;
                    if (goodsname == "") {
                        goodsName = "";
                    } else {
                        goodsName = "'" + goodsname + "'";
                    }
                    String orderstarttime = (String) map.get("orderStartTime");
                    String orderStartTime = null;
                    if (orderstarttime == "") {
                        orderStartTime = "";
                    } else {
                        orderStartTime = "'" + orderstarttime + "'";
                    }
                    String orderendtime = (String) map.get("orderEndTime");
                    String orderEndTime = null;
                    if (orderendtime == "") {
                        orderEndTime = "";
                    } else {
                        orderEndTime = "'" + orderendtime + "'";
                    }
                    String allOrderStatus = null;
                    Integer status = Integer.parseInt(map.get("status") + "");

                    List<OrderDetailsVO> orderList = this.baseMapper.queryRecycleBinByOrderBaseExcel(virtualGoods, Integer.valueOf(shopId), allOrderStatus,
                            status, userName, orderNum, goodsName, orderStartTime, orderEndTime);

                    String[] title = {"订单号", "下单时间","买家", "订单金额", "交易状态"};
                    List<Map<String, String>> list = Lists.newArrayList();
                    for (int i = 0; i < orderList.size(); i++) {
                        Integer orderStatus = orderList.get(i).getOrderStatus();
                        String statusName = null;
                        if (orderStatus == 1) {
                            statusName = "待付款";
                        } else if (orderStatus == 2) {
                            statusName = "待配货";
                        } else if (orderStatus == 3) {
                            statusName = "待发货";
                        } else if (orderStatus == 4) {
                            statusName = "已发货";
                        } else if (orderStatus == 5) {
                            statusName = "已签收";
                        } else if (orderStatus == 6) {
                            statusName = "已完成";
                        } else if (orderStatus == 7) {
                            statusName = "已取消";
                        } else if (orderStatus == 8) {
                            statusName = "退款中";
                        } else if (orderStatus == 9) {
                            statusName = "退款完成";
                        }

                        HashMap<String, String> mPut = Maps.newHashMap();
                        mPut.put("订单号", orderList.get(i).getOrderId());
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String format2 = format.format(orderList.get(i).getOrderCreateTime());
                        mPut.put("下单时间", format2);
                        mPut.put("买家", orderList.get(i).getBuyerUserName());
                        mPut.put("订单金额", new BigDecimal(orderList.get(i).getOrderPaymentAmount()).toString());
                        mPut.put("交易状态", statusName);
//
                        list.add(mPut);
                    }
                    /* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 *//* 此处key对应每一列的标题 */
                    Map<String, List<Map<String, String>>> m = Maps.newHashMap();
                    m.put("测试合并数据", list);
                    String url = ExcelsUtil.createExcel(title, m, new int[]{0});/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */

                    return ResponseResult.success(url);
                } else {
                    return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
                }
            } catch (Exception e) {

                e.printStackTrace();
                log.info("RecycleBinPageByOrderDetailsErrorResults:" + e.getMessage());
                return ResponseResult.fail(e.getMessage());
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }

    }

    @Override
    public ResponseResult queryLogisticsName(Map<Object, Object> map) {
        String token = map.get("token").toString();
        UserInfoVO userInfoVO = ParseTokenUtils.getUserInfoByToken(token);
        if (userInfoVO == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        String orderId = (String) map.get("orderId");
        // 查询买家收货地址
        OrderBaseEntity qln = this.baseMapper.selectById(orderId);
        String userName = qln.getOrderReceiverName();
        Integer expressId = qln.getOrderShippingExpressId();
        if (expressId != null) {
            //查询快递公司名字
            ResponseResult express = baseServiceClient.getBaseExpressInfoById(expressId);
            if (null != express && null != express.getData() && org.apache.commons.lang.StringUtils.isNotEmpty(express.getData().toString())) {
                Map<String, String> shipperCode = JSONObject.parseObject(JSON.toJSONString(express.getData()), Map.class);
                qln.setOrderShippingExpress(shipperCode.get("expressName"));
            } else {
                qln.setOrderShippingExpress(null);
            }
        } else {
            expressId = null;
            //自有快递
            qln.setOrderShippingExpressId(null);
        }
        return ResponseResult.success(qln);
    }

    @Override
    @Transactional
    public ResponseResult changeShoppingPrice(Map<String, Object> map) {
        String token = (String) map.get("token");
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (!isExistToken) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
        if (null == ui.getShopId()) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        String orderId = (String) map.get("orderId");
        List<Map<String,Object>> list = (List) map.get("list");
        for (Map<String,Object> res : list) {
            // 增加或减少的金额
            String money = (String) res.get("money");
            if (!MathUtil.isMoney(money)) {
                return ResponseResult.fail(2, "输入的格式有误,请按要求填写！");
            }
            // 类型转换
            BigDecimal price = new BigDecimal(money);
            // 金额正负1:+  2:-
            Integer type = (Integer) res.get("type");
            // 商品id
            Integer goodsId = (Integer) res.get("goodsId");
            // 查询该订单总价
            OrderGoodsEntity goodsEntity = orderGoodsMapper.selectOne(new LambdaQueryWrapper<OrderGoodsEntity>()
                    .eq(OrderGoodsEntity::getOrderId, orderId).eq(OrderGoodsEntity::getGoodsId, goodsId));
            OrderBaseEntity baseEntity = this.baseMapper.selectOne(new LambdaQueryWrapper<OrderBaseEntity>()
                    .eq(OrderBaseEntity::getOrderId, orderId));
            goodsEntity.setOrderGoodsAdjustBeforePrice(goodsEntity.getOrderGoodsAdjustBeforePrice() == null ? goodsEntity.getOrderGoodsPaymentAmount() : goodsEntity.getOrderGoodsAdjustBeforePrice());
            // 存储改价之后的金额
            BigDecimal calculateAfterMoney = new BigDecimal(0);
            BigDecimal newPrice = BigDecimal.ZERO;
            String adjustPrice = null;
            String adjustPriceBase = null;
            Integer isChangePrice = null;
            BigDecimal goodsPaymentPrice = this.baseMapper.queryGoodsPaymentPrice(orderId, goodsId);
            // 查询订单是否存在改价
            BigDecimal beforeAdjustPrice = this.baseMapper.queryBeforeAdjustPrice(orderId, goodsId);
            BigDecimal beforeAdjustBasePrice = this.baseMapper.queryOrderBaseBeforeAdjustPrice(orderId);
            if (null == beforeAdjustPrice) {
                isChangePrice = 0;
                beforeAdjustPrice = new BigDecimal(0);
            }
            if (null == beforeAdjustBasePrice) {
                beforeAdjustBasePrice = new BigDecimal(0);
            }else {
                beforeAdjustBasePrice = beforeAdjustBasePrice.subtract(beforeAdjustPrice);
            }
            BigDecimal totalPrice = baseEntity.getOrderPaymentAmount().subtract(goodsEntity.getOrderGoodsPaymentAmount())
                    .add(goodsEntity.getOrderGoodsAdjustBeforePrice());
            goodsPaymentPrice = goodsEntity.getOrderGoodsAdjustBeforePrice() == null ? goodsPaymentPrice : goodsEntity.getOrderGoodsAdjustBeforePrice();
            newPrice = price;
//            if (beforeAdjustPrice.compareTo(BigDecimal.ZERO) > 0 || beforeAdjustPrice.compareTo(BigDecimal.ZERO) == 0) {
//                // 当前参数大于0
//                if (type == 1) {
//                    newPrice = price.add(beforeAdjustPrice).setScale(3, RoundingMode.HALF_UP);
//                } else {
//                    newPrice = beforeAdjustPrice.subtract(price).setScale(3, RoundingMode.HALF_UP);
//                }
//            } else {
//                if (type == 1) {
//                    // 当前参数小于0
//                    newPrice = price.add(beforeAdjustPrice).setScale(3, RoundingMode.HALF_UP);
//                } else {
//                    // 当前参数小于0
//                    newPrice = price.negate().add(beforeAdjustPrice).setScale(3, RoundingMode.HALF_UP);
//                }
//            }
            if (type == 1) {
                calculateAfterMoney = totalPrice.add(price);
                beforeAdjustBasePrice = beforeAdjustBasePrice.add(price);
                adjustPrice = "" + newPrice;
                adjustPriceBase = "" + beforeAdjustBasePrice;
                price = goodsEntity.getOrderGoodsAdjustBeforePrice().add(price);
                // 更新goods实付金额
                this.baseMapper.updateOrderGoodsPaymentAmountAdd(orderId, price, adjustPrice, goodsId, isChangePrice);
            } else {
                if (goodsPaymentPrice.compareTo(price) < 0) {
                    return ResponseResult.fail(10060, "请注意，改价金额不得大于实付金额！");
                } else {
                    calculateAfterMoney = totalPrice.subtract(price);
                    beforeAdjustBasePrice = beforeAdjustBasePrice.subtract(price);
                    adjustPrice = "-" + newPrice;
                    adjustPriceBase = beforeAdjustBasePrice.toString();
                    price = goodsEntity.getOrderGoodsAdjustBeforePrice().subtract(price);
                    // 更新goods实付金额
                    this.baseMapper.updateOrderGoodsPaymentAmountSubtract(orderId, price, adjustPrice, goodsId, isChangePrice);
                }
            }
            // 更新base实付金额
            this.baseMapper.updateOrderBasePaymentAmount(orderId, calculateAfterMoney, adjustPriceBase);
            AdjustPriceDTO ap = new AdjustPriceDTO();
            ap.setOrderId(orderId);
            ap.setCalculateAfterMoney(calculateAfterMoney);
            // 更新record表与trade表实付金额
            this.updateOrderPaymentAmount(ap);
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult cancelShopGateRecord(PageUserTokenBeanDTO page) {
        Map<String, Object> map = new HashMap<>();
        IPage<QueryCancelRecordResultVO> result =new Page<>();
        Integer totalCount = null;
        boolean isExist = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + page.getToken());
        if (isExist) {
            try {


                UserInfoVO ui =ParseTokenUtils.getUserInfoByToken(page.getToken());
                page.setShopId(ui.getShopId());
                Map data= ParseMapUtils.beanToMap(page);
                //IsCance 为null 查询全部  IsCance 0 查询已核销  1  未核销
                if (null == page.getIsCancel()) {
                    result=this.baseMapper.queryCancelShopGateRecord2(new Query<QueryCancelRecordResultVO>().getPage(data),
                            page);

                    for (QueryCancelRecordResultVO vo : result.getRecords()) {
                        vo.setUserName(ui.getUserName());
                    }
                } else {
                    result=this.baseMapper.queryCancelShopGateRecord(new Query<QueryCancelRecordResultVO>().getPage(data),
                            page);
                    for (QueryCancelRecordResultVO vo : result.getRecords()) {
                        vo.setUserName(ui.getUserName());
                    }

                }

               return ResponseResult.success(PageUtils.getPage(result));

            } catch (IllegalAccessException e) {
                return ResponseResult.fail(e.getMessage());
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }

    }

    @Override
    public ResponseResult queryVirtualGoodsUser(PageUserTokenBeanDTO page) {
        List<Map<String, Object>> resultList = new ArrayList();
        List<String> userids = new ArrayList<>();
        Integer totalCount = null;
        Map<String, Object> map = new HashMap<>();
        boolean isExist = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + page.getToken());
        if (isExist) {
            // 获取user信息
            String userinfo = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + page.getToken());
            UserInfoDTO ui = JSON.parseObject(userinfo, UserInfoDTO.class);
            UserInfoVO userInfo = ui.getUser();
            page.setPage((page.getPage() - 1) * page.getLimit());
            page.setShopId(userInfo.getShopId());
            //IsCance 为null 查询全部  IsCance 0 查询已核销  1  未核销
            if (null == page.getIsCancel()) {
                userids = this.baseMapper.queryVirtualGoodsUser2(page);
                totalCount = this.baseMapper.queryVirtualGoodsUserCount2(page);
            } else {
                userids = this.baseMapper.queryVirtualGoodsUser(page);
                totalCount = this.baseMapper.queryVirtualGoodsUserCount(page);
            }
            if (null != userids) {
                for (String userid : userids) {
                    Map<String, Object> resutlMap = this.baseMapper.selectMembershipUserById(userid);
                    if (null != resutlMap) {
                        resultList.add(resutlMap);
                    }
                }
                map.put("totalCount", totalCount);
                map.put("userInfo", resultList);
                return ResponseResult.success(map);
            }
            return ResponseResult.fail(2, "未查询到数据信息");
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);

    }

    @Override
    public ResponseResult cancelRecord(PageUserTokenBeanDTO page) {
        boolean isExist = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + page.getToken());
        if (isExist) {
            // 获取user信息
            String userinfo = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + page.getToken());
            UserInfoDTO ui = JSON.parseObject(userinfo, UserInfoDTO.class);
            UserInfoVO userInfo = ui.getUser();
            //IsCance 为null 查询全部  IsCance 0 查询已核销  1  未核销
            Page<QueryCancelRecordResultVO> pageQuery = new Page<>(page.getPage(), page.getLimit());
            IPage<QueryCancelRecordResultVO> results = null;
            Map<String, Object> map = new HashMap<>();
            map.put("userId", page.getUserId());
            map.put("shopId", userInfo.getShopId());
            if (null == page.getIsCancel()) {
                results = this.baseMapper.queryCancelRecord2(pageQuery, map);
            } else {
                map.put("isCancel", page.getIsCancel());
                results = this.baseMapper.queryCancelRecord(pageQuery, map);
            }
            for (QueryCancelRecordResultVO result : results.getRecords()) {
                result.setUserName(userInfo.getUserName());
            }
            Map<String, Object> map2 = new HashMap<>();
            map2.put("totalCount", results.getTotal());
            map2.put("results", results.getRecords());
            return ResponseResult.success(map2);
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
    }

    @Override
    public ResponseResult queryOrdersByPC(Map<String, Object> map) {
        PageInfo pi = new PageInfo();
        String token = (String) map.get("token");
        // 获取user信息
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        if (userInfo != null) {
            String userId = userInfo.getUserId();
            // 订单状态
            Integer orderStatus = Integer.parseInt(map.get("orderStatus") + "");
            //订单编号
            String orderIds = (String) map.get("orderNo");
            //开始时间
            String orderStartTime = (String) map.get("timeStart");
            //结束时间
            String orderEndTime = (String) map.get("timeEnd");
            //用户
            String buyUserId = (String) map.get("buyUserId");
            //支付编码
            Integer payCode = map.get("payCode") != null ? Integer.parseInt(map.get("payCode") + "") : null;
            Integer virtualGoods = null;
            if (null != map.get("virtualGoods")) {
                virtualGoods = (Integer) map.get("virtualGoods");
            }
            Integer integralGoods = null;
            if (null != map.get("integralGoods")) {
                integralGoods = (Integer) map.get("integralGoods");
            }

            String allOrders = null;
            if (orderStatus.equals(CommonType.orderStatus.TO_BE_PAID.getCode())) {
                // 全部订单
                allOrders = "' '";
            }
            Integer orderStatusNum = getOrderStatusNum(orderStatus);

            Map<String, String> businessUseMap = new HashMap<>();
            businessUseMap.put("userId", userId);
            //根据用户id查企业用户信息
            ResponseResult businessResult = userServiceClient.getBusinessInfoByMap(businessUseMap);
            BusinessUserInfoDTO detail = null;
            if (businessResult.getCode() == 1){
                detail = JSON.parseObject(JSON.toJSONString(businessResult.getData()), BusinessUserInfoDTO.class);
            }

            //List<String> userIdList = getUserIdList(buyUserId, userId, detail);
            List<String> userIdList = new ArrayList<>();
                    //查询用户订单详情
            pi = getOrderList(map, integralGoods, orderIds, allOrders, orderStatusNum,
                    orderStartTime, orderEndTime, virtualGoods, payCode,
                    userIdList, detail, userId);
            return ResponseResult.success(pi);
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
    }

    @Override
    public ResponseResult print(Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<HtmlPrintVO> json = new ArrayList<>();
        List<PrintTemplateVO> print = new ArrayList<>();
        String htmlId = null;
        // 获取订单id集合
        ArrayList orderIds = (ArrayList) map.get("OrderIds");
        // 获取 发货地址id
        int shippingAddressId = (int) map.get("shippingAddressId");
        // 获取选择快递的拼音
        String shoppingvalue = (String) map.get("shoppingvalue");
        int shopId = (int) map.get("shopId");// 根据店铺id
        if ((orderIds) == null || (orderIds).size() == 0) {
            return ResponseResult.fail(JSONSerializer.serialize(print),"订单号为空");
        }
        if ((shippingAddressId + "") == null || (shippingAddressId + "").equals("") || shippingAddressId == 0) {
            return ResponseResult.fail(JSONSerializer.serialize(print),"发货地址不能为空");
        }

        if ((shoppingvalue) == null || (shoppingvalue).equals("") || shoppingvalue.equals("0")) {

            return ResponseResult.fail(JSONSerializer.serialize(print),"快递公司不能为空");
        }

        if ((shopId + "") == null || (shopId + "").equals("")) {
            return ResponseResult.fail(JSONSerializer.serialize(print),"店鋪id不能为空");
        }
        ShopkdniaoVO shopkdniao = this.baseMapper.queryKdniaoConfig(shopId);
        if (shopkdniao == null || shopkdniao.equals("")) {

            return ResponseResult.fail(JSONSerializer.serialize(print),"账号不存在,请到“商家中心=>店铺”中进行设置！");
        }
        String EBussinessID= shopkdniao.getEbussinessid();
        if (EBussinessID == null || EBussinessID.equals("")) {
            return ResponseResult.fail(JSONSerializer.serialize(print),"电商号为空,请到“商家中心=>店铺”中进行设置！");
        }
        String AppKey = shopkdniao.getAppkey();

        if (AppKey == null || AppKey.equals("")) {

            return ResponseResult.fail(JSONSerializer.serialize(print),"快递鸟秘钥为空,请到“商家中心=>店铺”中进行设置！");
        }

        // 根据店铺id获取EBussinessID和AppKey
        ShopdpexpressVO Shopdpexpress = this.baseMapper.queryShopdexpress(shopId);
        // 根据店铺id获取快递公司给的秘钥等
        if (Shopdpexpress == null || Shopdpexpress.equals("")) {
            return ResponseResult.fail(JSONSerializer.serialize(print),"未选择快递公司,请到“商家中心=>店铺”中进行设置！");
        }
        KdniaoExpressVO express = this.baseMapper.querykdniaoExpressByparam(shoppingvalue);

        ShopShippingAddressVO shopaddress = this.baseMapper.selectShippingAddress(shippingAddressId);

        OrderBaseEntity uporderAddress = new OrderBaseEntity();

        uporderAddress.setOrderSellerAddress(shopaddress.getShippingAddressAddress());
        uporderAddress.setOrderSellerContact(shopaddress.getShippingAddressPhone());
        uporderAddress.setOrderSellerName(shopaddress.getShippingAddressContact());
        // 拿去orderID列表
        List<OrderBaseEntity> orderBases = new ArrayList<OrderBaseEntity>();
        for (int i = 0; i < orderIds.size(); i++) {
            uporderAddress.setOrderId((String) orderIds.get(i));
            int ope = this.baseMapper.updateById(uporderAddress);
            // 跟新订单
            OrderBaseEntity Bases = this.baseMapper.selectById((String) orderIds.get(i));
            orderBases.add(Bases);
        }

        for (OrderBaseEntity bas : orderBases) {
            // 判断订单信息是否有此人，防止空
            if (bas == null || bas.equals("")) {
                if ((print.size()) > 0) {
                    return ResponseResult.fail(JSONSerializer.serialize(print),"生成部分订单失败！");
                } else {
                    // 循环请求第一次接口时，当出现false错误的信息时，判断是否有请求成功的订单，如果有打印请求成功的面单，跳出循环
                    return ResponseResult.fail(JSONSerializer.serialize(print),"生成订单失败!");
                }
            }
            BaseDistrictVO Senderprovinces = this.baseMapper.selectOrderArea(shopaddress.getShippingAddressProvinceId());
            BaseDistrictVO Sendercity = this.baseMapper.selectOrderArea(shopaddress.getShippingAddressCityId());
            BaseDistrictVO Senderarea = this.baseMapper.selectOrderArea(shopaddress.getShippingAddressAreaId());

            BaseDistrictVO provinces = this.baseMapper.selectOrderArea(bas.getOrderReceiverProvinceId());
            // 根据省市区查询地址
            BaseDistrictVO city = this.baseMapper.selectOrderArea(bas.getOrderReceiverCityId());
            BaseDistrictVO area = this.baseMapper.selectOrderArea(bas.getOrderReceiverAreaId());
            // 根据区域Id查询收获区的省市区
            List<OrderGoodsEntity> ordergood = orderGoodsMapper.selectList(new LambdaQueryWrapper<OrderGoodsEntity>()
                                              .eq(OrderGoodsEntity::getOrderId,bas.getOrderId()));
            // 根据请求商品参数，生成josn数组
            List<CommodityVO> ordergoodsList = new ArrayList<CommodityVO>();

            for (OrderGoodsEntity good : ordergood) {
                CommodityVO comm = new CommodityVO();
                comm.setGoodsName(good.getGoodsName());
                comm.setGoodsquantity(good.getOrderGoodsNum());
                ordergoodsList.add(comm);
            }
            String ordergoodsListjson = JSON.toJSONString(ordergoodsList);
            ordergoodsListjson = ordergoodsListjson.replaceAll("\"", "\'");
            // 将list对象转化为json
            KdGoldAPIUtils demo = new KdGoldAPIUtils();
            String requestData = "{'OrderCode': '" + bas.getOrderId() + "'," + "'ShipperCode':'" + shoppingvalue + "',"
                    +

                    "'CustomerName':'" + Shopdpexpress.getCustomerName() + "'," + "'CustomerPwd':'"
                    + Shopdpexpress.getCustomerPwd() + "'," + "'MonthCode':'" + Shopdpexpress.getMonthCode() + "',"
                    + "'LogisticCode':'" + Shopdpexpress.getLogisticCode() + "'," + "'SendSite':'"
                    + Shopdpexpress.getSendSite() + "'," + "'SendStaff':'" + Shopdpexpress.getSendStaff() + "',"
                    + "'PayType':1," + "'ExpType':1," + "'Cost':'" + bas.getOrderShippingFee() + "'," + "'IsNotice':1,"
                    +
                    // 是否通知快递揽件

                    "'Sender':" + "{" + "'Company':'" + bas.getShopName() + "'," + "'Name':'" + bas.getSellerUserName()
                    + "'," + "'Mobile':'" + bas.getOrderSellerContact() + "','" + "ProvinceName':'"
                    + Senderprovinces.getDistrictName() + "','CityName':'" + Sendercity.getDistrictName()
                    + "','ExpAreaName':'" + Senderarea.getDistrictName() + "','Address':'"
                    + shopaddress.getShippingAddressAddress() + "'}," + "'Receiver':" +

                    "{" + "'Name':'" + bas.getOrderReceiverName() + "'," + "'Mobile':'" + bas.getOrderReceiverContact()
                    + "'," + "'ProvinceName':'" + provinces.getDistrictName() + "'," + "'CityName':'"
                    + city.getDistrictName() + "'," + "'ExpAreaName':'" + area.getDistrictName() + "'," + "'Address':'"
                    + bas.getOrderReceiverAddress() + "'}," + "'Commodity':" + ordergoodsListjson + ","
                    + "'Quantity':1," +

                    "'Remark':'" + bas.getOrderMessage() + "'," + "'IsReturnPrintTemplate':1}";
            try {
                htmlId = demo.orderOnlineByJson(EBussinessID,AppKey,requestData);
                if (htmlId.indexOf("false") > 0) {

                    if ((print.size()) > 0) {

                        return ResponseResult.fail(JSONSerializer.serialize(print),"生成部分订单失败!");
                    } else {
                        // 循环请求第一次接口时，当出现false错误的信息时，判断是否有请求成功的订单，如果有打印请求成功的面单，跳出循环
                        return ResponseResult.fail(JSONSerializer.serialize(print),"生成订单失败，请确定快递网点密钥是否有误！");

                    }

                }
                HtmlPrintVO html = new HtmlPrintVO();
                html = JSON.parseObject(htmlId, new TypeReference<HtmlPrintVO>() {
                });
                // 將json字符串转对象象的方法
                PrintTemplateVO p = new PrintTemplateVO();
                p.setPrintTemplate(html.getPrintTemplate());
                json.add(html);
                print.add(p);
                // 以上都是便利orderId，调用快递鸟接口生成多个电子面单记录

                String LogisticCode = htmlId.substring(htmlId.indexOf("LogisticCode") + 17,
                        htmlId.indexOf("LogisticCode") + 35);

                LogisticCode=LogisticCode.substring(0,LogisticCode.indexOf("\""));

                // 截取订单编号
                OrderBaseEntity po = new OrderBaseEntity();
                po.setOrderId(bas.getOrderId());
                // 快递的id
                po.setOrderShippingExpressId(express.getId());
                po.setOrderShippingCode(LogisticCode);
                po.setOrderStatus(4);
                po.setOrderShippingTime(new Date());
                po.setOrderReceiverDate(DateUtils.addDays(new Date(),7));
                // 更新订单状态，时间等
                this.baseMapper.updateById(po);
                // 通过接口返回的报文判断是否生成成功
            } catch (Exception e) {
                return ResponseResult.fail(e.getMessage());
            }

            // 修改orderbase订单状态
            orderGoodsMapper.update(null,new LambdaUpdateWrapper<OrderGoodsEntity>()
                            .set(OrderGoodsEntity::getOrderGoodsStatus,4)
                            .eq(OrderGoodsEntity::getOrderId,bas.getOrderId()));
            this.baseMapper.updateUnionOrderState(bas.getOrderId());
            this.baseMapper.updateConsumeTradeState(bas.getOrderId());
            this.baseMapper.updateConsunmRecordState(bas.getOrderId());
        }
        return ResponseResult.success(JSONSerializer.serialize(print),"打印成功");
    }

    @Override
    public ResponseResult soldOrdersExp(Map<String, Object> map) {
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());
        if (ui == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
        }
        Integer shopId = Integer.valueOf(ui.getShopId());
        Integer status = map.get("status") == null ? 1 : Integer.parseInt(map.get("status").toString());
        //条件参数
        Map<String, Object> mapShop = new HashMap<>();
        mapShop.put("shopId", shopId);
        mapShop.put("userName", map.get("userName"));
        mapShop.put("orderNum", map.get("orderNum"));
        mapShop.put("orderStartTime", map.get("orderStartTime"));
        mapShop.put("orderEndTime", map.get("orderEndTime"));
        mapShop.put("orderType", map.get("orderType"));
        mapShop.put("code", CommonType.orderType.GOODS_TYPE.getCode());
        Integer otherOrderStatus = null;
        //退货状态
        Integer orderReturnStatus1 = null;
        //退款状态
        Integer orderRefundStatus1 = null;
        if (status == 1) {
        } else if (status == 2) {
            // 待付款
            otherOrderStatus = 1;
            orderReturnStatus1 = 0;
            orderRefundStatus1 = 0;
        } else if (status == 3) {
            // 已付款
            otherOrderStatus = 3;
            orderReturnStatus1 = 0;
            orderRefundStatus1 = 0;
        } else if (status == 4) {
            // 已发货
            otherOrderStatus = 4;
            orderReturnStatus1 = 0;
            orderRefundStatus1 = 0;
        } else if (status == 5) {
            // 已完成
            otherOrderStatus = 6;
            orderReturnStatus1 = 0;
            orderRefundStatus1 = 0;
        } else if (status == 6) {
            // 已取消
            otherOrderStatus = 7;
            orderReturnStatus1 = 0;
            orderRefundStatus1 = 0;
        } else if (status == 7) {
            // 退货中
            otherOrderStatus = null;
            orderReturnStatus1 = 1;
        } else if (status == 8) {
            // 退款中
            otherOrderStatus = null;
            orderRefundStatus1 = 1;
        } else if (status == 9) {
            // 退款完成
            otherOrderStatus = null;
            orderRefundStatus1 = 2;
        } else if (status == 10) {
            // 退货完成
            otherOrderStatus = null;
            orderReturnStatus1 = 2;
        }
        mapShop.put("otherOrderStatus", otherOrderStatus);
        mapShop.put("orderReturnStatus", orderReturnStatus1);
        mapShop.put("orderRefundStatus", orderRefundStatus1);
        List<SoldOrderExportDTO> orderList = this.baseMapper.queryOrderBaseOfShopList(mapShop);

        String[] title = {"订单号", "买家昵称", "收件人姓名", "手机", "电话", "省", "市", "区", "地址", "邮编", "运费", "实付款", "商品名称",
                "商家编码", "销售属性", "单价", "数量", "优惠", "下单时间", "付款时间", "买家留言", "卖家备注"};
        List<Map<String, String>> list = Lists.newArrayList();
        for (SoldOrderExportDTO soldOrderExportDTO : orderList) {
            Integer orderStatus = soldOrderExportDTO.getOrderStatus();
            String statusName = null;
            if (orderStatus == 1) {
                statusName = "待付款";
            } else if (orderStatus == 2) {
                statusName = "待配货";
            } else if (orderStatus == 3) {
                statusName = "待发货";
            } else if (orderStatus == 4) {
                statusName = "已发货";
            } else if (orderStatus == 5) {
                statusName = "已签收";
            } else if (orderStatus == 6) {
                statusName = "已完成";
            } else if (orderStatus == 7) {
                statusName = "已取消";
            } else if (orderStatus == 8) {
                statusName = "退款中";
            } else if (orderStatus == 9) {
                statusName = "退款完成";
            }
            soldOrderExportDTO.setOrderStatusName(statusName);
            HashMap<String, String> mPut = Maps.newHashMap();
            mPut.put("订单号", soldOrderExportDTO.getOrderId());
            mPut.put("订单状态", soldOrderExportDTO.getOrderStatusName());
            mPut.put("买家昵称", soldOrderExportDTO.getBuyerUserName());
            mPut.put("收件人姓名", soldOrderExportDTO.getOrderReceiverName());
            mPut.put("手机", soldOrderExportDTO.getOrderReceiverContact());
            mPut.put("电话", null);
            mPut.put("省", soldOrderExportDTO.getProvince());
            mPut.put("市", soldOrderExportDTO.getCity());
            mPut.put("区", soldOrderExportDTO.getArea());
            mPut.put("地址", soldOrderExportDTO.getOrderReceiverAddress());
            mPut.put("邮编", null);
            mPut.put("运费", soldOrderExportDTO.getOrderShippingFee() == null ? "0" : soldOrderExportDTO.getOrderShippingFee().toString());
            mPut.put("实付款", soldOrderExportDTO.getOrderPaymentAmount().toString());
            mPut.put("商品名称", soldOrderExportDTO.getGoodsName());
            mPut.put("商家编码", soldOrderExportDTO.getShopId());
            mPut.put("销售属性", soldOrderExportDTO.getOrderSpecChineseValue());
            mPut.put("单价", soldOrderExportDTO.getGoodsPrice().toString());
            mPut.put("数量", soldOrderExportDTO.getOrderGoodsNum().toString());
            mPut.put("优惠", soldOrderExportDTO.getOrderDiscountFee() == null ? "0" : soldOrderExportDTO.getOrderDiscountFee().toString());
            mPut.put("下单时间", soldOrderExportDTO.getOrderCreateTime());
            mPut.put("付款时间", soldOrderExportDTO.getPaymentTime());
            mPut.put("买家留言", soldOrderExportDTO.getOrderMessage());
            mPut.put("卖家备注", soldOrderExportDTO.getOrderSellerMessage());
            list.add(mPut);
        }
        /* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 *//* 此处key对应每一列的标题 */
        Map<String, List<Map<String, String>>> m = Maps.newHashMap();
        m.put("测试合并数据", list);
        String url = ExcelsUtil.createExcel(title, m, new int[]{0});
        return ResponseResult.success(url);
    }

    @Override
    public ResponseResult checkodd(Map<String, Object> map) {
        //判断是订单号还是投诉单号
        String oddNumbers = String.valueOf(map.get("oddNumbers"));
        Integer shopId = (Integer) map.get("shopId");
        OrderStatusVO selectorderid = null;
        if (oddNumbers != null && oddNumbers != "" && PayToolUtil.isInteger(oddNumbers)) {
            //纯数字订单
            selectorderid = this.baseMapper.selectorderid(oddNumbers,shopId);
            if (selectorderid != null){
                Integer normalStatus = selectorderid.getOrderStatus();
                Integer orderRefundStatus = selectorderid.getOrderRefundStatus();
                Integer orderReturnStatus = selectorderid.getOrderReturnStatus();
                Integer status = selectorderid.getOrderStatus();
                if (normalStatus == 3 ) {
                    // 未发货状态
                    if (orderRefundStatus == 1 || orderRefundStatus == 3) {
                        // 未发货退款中
                        status = 22;
                    } else if (orderRefundStatus == 2) {
                        // 商家拒绝或审核通过，继续发货，但不可再次申请退款
                        status = 26;
                    } else if (orderRefundStatus == 0 ) {
                        status = normalStatus;
                    } else{
                        status = 3;
                    }
                } else if (normalStatus == 6) {
                    // 已完成状态
                    if (orderRefundStatus == 1 || orderRefundStatus == 3) {
                        // 收货退款中
                        status = 22;
                    } else if (orderRefundStatus == 2) {
                        //收货退款完成
                        status = 26;
                    } else if (orderRefundStatus == 0 && orderReturnStatus == 0) {
                        //无退货退款
                        status = 6;
                    } else if (orderReturnStatus == 1 || orderReturnStatus == 3) {
                        //} else if (orderReturnStatus == 1 ) {
                        // 收货退货中
                        status = 24;
                    } else if (orderReturnStatus == 2) {
                        //退货完成
                        status = 25;
                    } else if (orderReturnStatus == 0 && orderRefundStatus == 0) {
                        status = 6;
                    }else{
                        status = 6;
                    }
                } else {
                    status = normalStatus;
                }
                selectorderid.setOrderStatus(status);
            }
        }else{
            selectorderid = this.baseMapper.selectcomplaintsid(oddNumbers,shopId);
        }
        if (selectorderid == null){
            return ResponseResult.fail(0, "订单号/投诉单号不存在",selectorderid);
        }
        return ResponseResult.success("订单号/投诉单号存在",selectorderid);
    }

    @Override
    public ResponseResult queryNotEvaluatedOrder() {
        List<AcquiescenceVO> acquiescenceVOList = this.baseMapper.queryNotEvaluatedOrder();
        return ResponseResult.success(acquiescenceVOList);
    }


    private PageInfo getOrderList(Map<String, Object> map, Integer integralGoods, String orderIds, String allOrders, Integer orderStatusNum, String orderStartTime,
                                  String orderEndTime, Integer virtualGoods, Integer payCode,
                                  List<String> userIdList, BusinessUserInfoDTO detail, String userId) {
        PageInfo pi = new PageInfo();
        List userIds = new ArrayList();
        userIds.add(userId);

        Map<String, Object> mapOrder = new HashMap<>();
        mapOrder.put("integralGoods", integralGoods);
        mapOrder.put("orderIds", orderIds);
        mapOrder.put("allOrders", allOrders);
        mapOrder.put("orderStatusNum", orderStatusNum);
        mapOrder.put("orderStartTime", orderStartTime);
        mapOrder.put("orderEndTime", orderEndTime);
        mapOrder.put("virtualGoods", virtualGoods);
        mapOrder.put("orderType", null);
        mapOrder.put("payCode", payCode);
        mapOrder.put("userIdList", userIds);
        //查询用户订单详情
        IPage<OrderListVO> page = this.baseMapper.queryOrderList(new Query<OrderListVO>().getPage(map), mapOrder);

        List<String> gradeNameList = new ArrayList<>();
        List<Integer> hyZheKouList = new ArrayList<>();
        for (int i = 0; i < page.getRecords().size(); i++) {
            Date endTime = page.getRecords().get(i).getSeckillCancelTime() == null ?
                    DateUtils.addDays(page.getRecords().get(i).getOrderCreateTime(),1) : page.getRecords().get(i).getSeckillCancelTime();
            page.getRecords().get(i).setOrderEndTime(endTime);
            String giveawayInfo = page.getRecords().get(i).getGiveawayInfo();
            List<FullReductionGiftsVO> list = new ArrayList<>();
            if (null != giveawayInfo && !giveawayInfo.isEmpty()) {
                list = JsonUtils.string2Obj(giveawayInfo, List.class, FullReductionGiftsVO.class);
            }
            page.getRecords().get(i).setZengpinInfo(list);
            //判断是否可以再申请售后
            Integer platformInterventionId = page.getRecords().get(i).getPlatformInterventionId();
            Integer interventionState = page.getRecords().get(i).getInterventionState();
            Integer processingResults = page.getRecords().get(i).getProcessingResults();
            Integer returnMethodType = page.getRecords().get(i).getReturnMethodType();
            if (platformInterventionId != null && interventionState == 2 && processingResults == 0 && returnMethodType == 1) {
                page.getRecords().get(i).setPlatformAudit(1);
            } else if (platformInterventionId != null && interventionState == 2 && processingResults == 0 && (returnMethodType == 2 || returnMethodType == 3)) {
                page.getRecords().get(i).setPlatformAudit(2);
            } else {
                page.getRecords().get(i).setPlatformAudit(0);
            }
            Integer goodsNum = 0;
            //退款状态
            Integer orderRefundStatus = page.getRecords().get(i).getOrderRefundStatus();
            //退货状态
            Integer orderReturnStatus = page.getRecords().get(i).getOrderReturnStatus();

            //是否虚拟商品
            Integer isVirtualGoods = page.getRecords().get(i).getVirtualGoods();
            Integer isPastDue = page.getRecords().get(i).getPastDue();
            //判断虚拟商品是否过期且允许退款
            if (isVirtualGoods.equals(CommonType.commonStatus.NO.getCode())
                    && !DateUtils.compareDate2(Objects.requireNonNull(DateUtils.parseCNDate(page.getRecords().get(i).getPeriodOfValidity())))
                    && isPastDue.equals(CommonType.commonStatus.YES.getCode())) {
                page.getRecords().get(i).setExpire(CommonType.commonStatus.YES.getCode());
            }

            // 订单状态
            Integer normalStatus = page.getRecords().get(i).getOrderStatus();
            // 涉及退款退货订单状态
            Integer status = getStatus(normalStatus, virtualGoods, orderRefundStatus, orderReturnStatus, page.getRecords().get(i).getOrderLastReturnTime());
            // 存放最新状态
            page.getRecords().get(i).setOrderStatus(status);
            //判断店铺是否设置合同
            ResponseResult shopContractRest = businessServiceClient.getShopContract(page.getRecords().get(i).getShopId());
            ShopContractDTO shopContract = JSON.parseObject(JSON.toJSONString(shopContractRest.getData()), ShopContractDTO.class);
            if (shopContract != null && shopContract.getChapterImage() != null && !"".equals(shopContract.getChapterImage())) {
                page.getRecords().get(i).setIsShopContract(1);
            } else {
                page.getRecords().get(i).setIsShopContract(0);
            }
            //获取账号开户行，
            OrderInvoiceInfoEntity invoice = orderInvoiceInfoMapper.selectOne(new LambdaQueryWrapper<OrderInvoiceInfoEntity>()
                    .eq(OrderInvoiceInfoEntity::getOrderId, page.getRecords().get(i).getOrderId()));
            if (invoice != null) {
                page.getRecords().get(i).setBankAccount(invoice.getBankAccount());
                page.getRecords().get(i).setOpeningBank(invoice.getOpeningBank());
            } else {
                page.getRecords().get(i).setBankAccount("-");
                page.getRecords().get(i).setOpeningBank("-");
            }
            if (detail != null) {
                String business = detail.getCompanyName();
                if (business != null && !business.isEmpty()) {
                    page.getRecords().get(i).setBusinessName(business);
                } else {
                    page.getRecords().get(i).setBusinessName(page.getRecords().get(i).getBuyerUserName());
                }
            }
            String orderId = page.getRecords().get(i).getOrderId();
            //根据订单号查商品列表
            List<GoodsDetailsListVO> goodsDetailsList = orderGoodsMapper.queryGoodsListLimit(orderId);
            Integer goodsCount = orderGoodsMapper.selectCount(new LambdaQueryWrapper<OrderGoodsEntity>()
                    .eq(OrderGoodsEntity::getOrderId, orderId)
                    .eq(OrderGoodsEntity::getOrderDel, CommonType.orderDel.NOT_DELETE.getCode()));
            page.getRecords().get(i).setGoodsDetailsCount(Math.max(goodsCount - goodsDetailsList.size(), 0));
            // 商品总价
            BigDecimal paymentPrice = new BigDecimal(0);
            Integer offSelfCount = 0;
            for (GoodsDetailsListVO goodsDetailsListVO : goodsDetailsList) {
                // 计算共有几件商品
                Integer goodsnum = goodsDetailsListVO.getOrderGoodsNum();
                goodsNum += goodsnum;
                page.getRecords().get(i).setGoodsNum(goodsNum);
                // 单个商品价格
                BigDecimal orderGoodsAmount = goodsDetailsListVO.getOrderGoodsAmount();
                paymentPrice = paymentPrice.add(orderGoodsAmount).setScale(2, RoundingMode.UP);

                ShopMemberVO shopMember = new ShopMemberVO();

                shopMember.setShopId(goodsDetailsListVO.getShopId());
                shopMember.setUserId(userId);
                ResponseResult gradeResult = businessServiceClient.getGradeByIds(shopMember);
                String gradeName = (String) gradeResult.getData();
                gradeNameList.add(gradeName);
                //int discount = (int) businessServiceClient.findMemberDiscount(Integer.valueOf(goodsDetailsListVO.getShopId()), userId).getData();
                //查找会员等级折扣
                hyZheKouList.add(null);
                //判断是否下架
//                if (goodsDetailsListVO.getGoodsIsShelves() == 2 || goodsDetailsListVO.getGoodsStock() == 0) {
//                    offSelfCount++;
//                }
            }
            // 再来一单
            page.getRecords().get(i).setIsAnotherOrder(offSelfCount.equals(goodsCount));
            // 商品列表
            page.getRecords().get(i).setGoodsDetailsList(goodsDetailsList);
            // 退款实际价格
            page.getRecords().get(i).setRefundRealPrice(page.getRecords().get(i).getOrderPaymentAmount());
            // 总付款价格
            page.getRecords().get(i).setOrderTotalPrice(page.getRecords().get(i).getOrderPaymentAmount());
            // 向redis存入订单状态
            Integer statusNum = page.getRecords().get(i).getOrderStatus();
            String statusNumber = statusNum.toString();
            if (!RedisUtil.exists(YFConfig.YF_ORDERSTATUS + "--" + orderId)) {
                RedisUtil.set(YFConfig.YF_ORDERSTATUS + "--" + orderId, statusNumber, 3000);
            } else {
                RedisUtil.remove(YFConfig.YF_ORDERSTATUS + "--" + orderId);
                RedisUtil.set(YFConfig.YF_ORDERSTATUS + "--" + orderId, statusNumber, 3000);
            }
        }
        pi.setPage(PageUtils.getPage(page));
        pi.setGradeNameList(gradeNameList);
        pi.setHyZheKouList(hyZheKouList);
        return pi;
    }

    private Integer getStatus(Integer normalStatus, Integer virtualGoods, Integer orderRefundStatus, Integer orderReturnStatus, String orderLastReturnTim) {
        // 涉及退款退货订单状态
        Integer status = null;
        if (normalStatus.equals(CommonType.orderStatus.TO_BE_SHIPPED.getCode()) || (null != virtualGoods && 0 == virtualGoods && CommonType.orderStatus.SHIPPED.getCode().equals(normalStatus))) {
            // 未发货状态
            if (orderRefundStatus.equals(CommonType.orderRefundStatus.REFUNDING.getCode()) || orderRefundStatus.equals(CommonType.orderRefundStatus.REFUND_FAILED.getCode())) {
                // 未发货退款中
                status = 22;
            } else if (orderRefundStatus.equals(CommonType.orderRefundStatus.REFUND_COMPLETED.getCode())) {
                // 商家拒绝或审核通过，继续发货，但不可再次申请退款
                status = 26;
            } else if (orderRefundStatus.equals(CommonType.orderRefundStatus.NO_REFUND.getCode()) && null != virtualGoods && 0 == virtualGoods) {
                status = normalStatus;
            } else {
                status = 3;
            }
        } else if (normalStatus.equals(CommonType.orderStatus.CONFIRM_RECEIPT.getCode())) {
            // 已完成状态
            if (orderRefundStatus.equals(CommonType.orderRefundStatus.REFUNDING.getCode()) || orderRefundStatus.equals(CommonType.orderRefundStatus.REFUND_FAILED.getCode())) {
                // 收货退款中
                status = 23;
            } else if (orderRefundStatus.equals(CommonType.orderRefundStatus.REFUND_COMPLETED.getCode())) {
                status = 25;
            } else if (orderRefundStatus.equals(CommonType.orderRefundStatus.NO_REFUND.getCode()) && orderReturnStatus.equals(CommonType.orderReturnStatus.NO_RETURNS.getCode())) {
                status = 6;
            } else if (orderReturnStatus.equals(CommonType.orderReturnStatus.RETURNING_GOODS.getCode()) || orderReturnStatus.equals(CommonType.orderReturnStatus.RETURN_FAILED.getCode())) {
                // 收货退货中
                status = 24;
            } else if (orderReturnStatus.equals(CommonType.orderReturnStatus.RETURN_COMPLETED.getCode())) {
                status = 25;
            } else {
                status = 6;
            }
            if (null != orderLastReturnTim && TimeStampUtil.compareDate(orderLastReturnTim, TimeStampUtil.getNowDate())) {
                // 订单超过完成时间不可售后
                status = 27;
            }
        } else {
            status = normalStatus;
        }

        return status;
    }


    private List<String> getUserIdList(String buyUserId, String userId, BusinessUserInfoDTO detail) {
        List<String> userIdList = new ArrayList<>();
        if (buyUserId != null) {
            userIdList.add(buyUserId);
        } else {
            userIdList.add(userId);
            if (detail != null) {
                //根据企业id查企业员工
                List<String> list = userServiceClient.queryEmployeesList(detail.getBusinessId().toString());
                if (list.contains(userId)) {
                    userIdList = list;
                }
            }
        }
        return userIdList;
    }



    private Integer getOrderStatusNum(Integer orderStatus) {
        Integer orderStatusNum = null;
        if (orderStatus.equals(CommonType.orderStatus.PAID.getCode())) {
            // 待付款
            orderStatusNum = CommonType.orderStatus.TO_BE_PAID.getCode();
        } else if (orderStatus.equals(CommonType.orderStatus.TO_BE_SHIPPED.getCode())) {
            // 待发货
            orderStatusNum = CommonType.orderStatus.TO_BE_SHIPPED.getCode();
        } else if (orderStatus.equals(CommonType.orderStatus.SHIPPED.getCode())) {
            // 待收货
            orderStatusNum = CommonType.orderStatus.SHIPPED.getCode();
        } else if (orderStatus.equals(CommonType.orderStatus.SIGNED_FOR.getCode())) {
            // 已取消
            orderStatusNum = CommonType.orderStatus.CANCEL.getCode();
        }
        return orderStatusNum;
    }


    /**
     * 更新record，trade实付金额
     *
     * @param ap
     * @return
     */
    public boolean updateOrderPaymentAmount(AdjustPriceDTO ap) {
        String orderId = ap.getOrderId();
        BigDecimal calculateAfterMoney = ap.getCalculateAfterMoney();
        boolean isUpdateRecord = this.baseMapper.updateOrderPaymentAmountByRecord(orderId, calculateAfterMoney);
        boolean isUpdateTrade = this.baseMapper.updateOrderPaymentAmountByTrade(orderId, calculateAfterMoney);
        if (isUpdateRecord && isUpdateTrade) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 设置待发货订单信息
     *
     * @param orderDetails
     * @return
     */
    private boolean setShippedOrderDetails(List<ShipmentsByOrderBaseVO> orderDetails) {
        for (int i = 0; i < orderDetails.size(); i++) {
            String orderId = orderDetails.get(i).getOrderId();
            // 退款状态
            Integer orderRefundStatus = orderDetails.get(i).getOrderRefundStatus();
            // 退货状态
            Integer orderReturnStatus = orderDetails.get(i).getOrderReturnStatus();
            // 订单状态
            Integer normalStatus = orderDetails.get(i).getOrderStatus();
            // 涉及退款退货订单状态
            Integer rStatus = null;
            //满减赠品信息
            String giveawayInfo = orderDetails.get(i).getGiveawayInfo();
            List<ManJianZengPinVO> list;
            if(null != giveawayInfo && !"".equals(giveawayInfo)) {
                list = JsonUtils.string2Obj(giveawayInfo, List.class, ManJianZengPinVO.class);
                orderDetails.get(i).setZengpinInfo(list);
            }
            if (normalStatus == 3) {
                // 未发货状态
                if (orderRefundStatus == 1) {
                    // 未发货退款中
                    rStatus = 22;
                } else if (orderRefundStatus == 2) {
                    // 商家拒绝或审核通过，继续发货，但不可再次申请退款
                    rStatus = 26;
                } else if (orderRefundStatus == 0) {
                    rStatus = 3;
                }
            } else if (normalStatus == 6) {
                // 已完成状态
                if (orderRefundStatus == 1) {
                    // 收货退款中
                    rStatus = 23;
                } else if (orderRefundStatus == 2) {
                    rStatus = 25;
                } else if (orderRefundStatus == 0 && orderReturnStatus == 0) {
                    rStatus = 6;
                } else if (orderReturnStatus == 1) {
                    // 收货退货中
                    rStatus = 24;
                } else if (orderReturnStatus == 2) {
                    rStatus = 25;
                } else {
                    rStatus = 6;
                }
            } else {
                rStatus = normalStatus;
            }
            // 存放最新状态
            orderDetails.get(i).setOrderStatus(rStatus);
            List<ShipmentsByOrderGoodsDetailsVO> queryOrderDetails = this.orderGoodsMapper.shipmentsByOrderGoods(orderId);
            if (queryOrderDetails != null) {
                orderDetails.get(i).setShipmentsByOrderGoodsDetails(queryOrderDetails);
            }
        }
        return true;
    }


    /**
     * 判断权限
     *
     * @param userInfo
     * @param limit
     * @return
     */
    public Boolean containLimits(UserInfoVO userInfo, String limit) {
        Integer adminInteger = userInfo.getSellerIsAdmin();
        if (1 == adminInteger) {
            return true;
        }
        String limitsString = userInfo.getLimits();
        if (null == limitsString) {
            return false;
        }
//		String[] limits = limitsString.split(",");
//		Set<String> limitsSet = new HashSet<String>(Arrays.asList(limits));
//		Boolean torf = limitsSet.contains(limit);
        return true;
    }

    @Override
    public ResponseResult queryMemberUserOrderDetail(Map<String, Object> map) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(map.get("token").toString());
        if (null != userInfo) {
            Integer returnFlag = 0;
            //分页查询数据
            IPage<UserInfoOrderDetailVO> page = this.baseMapper.queryMemberUserOrderDetail(new Query<UserInfoOrderDetailVO>().getPage(map), map);
            for(UserInfoOrderDetailVO r:page.getRecords()) {
                String orderId = r.getOrderId();
                OrderBaseEntity orderInfoEntity = this.baseMapper.selectById(orderId);
                Integer virtualGoods = orderInfoEntity.getVirtualGoods();
                Integer orderIsShopTake = orderInfoEntity.getOrderIsShopTake();
                if( null != orderIsShopTake && 1 == orderIsShopTake){
                    r.setOrderType(3);
                }else{
                    if(null != virtualGoods && 0 == virtualGoods){
                        r.setOrderType(2);
                        r.setPastDue(orderInfoEntity.getPastDue());
                        r.setIsCancel(orderInfoEntity.getIsCancel());
                    }else{
                        r.setOrderType(1);
                    }
                }
                int returnStatus = Integer.valueOf(orderInfoEntity.getOrderReturnStatus());
                int refundStatus =  Integer.valueOf(orderInfoEntity.getOrderRefundStatus());
                r.setReturnStatus(returnStatus);
                r.setRefundStatus(refundStatus);
                if (2 == returnStatus || 2 == refundStatus) {
                    BigDecimal returnAmount = new BigDecimal(orderInfoEntity.getOrderRefundAmount());
                    BigDecimal orderAmount = orderInfoEntity.getOrderPaymentAmount();
                    if (orderAmount.compareTo(returnAmount) > 0) {
                        returnFlag = 2;
                    } else if ((orderAmount.compareTo(returnAmount) == 0)) {
                        returnFlag = 1;
                    }
                }
                r.setReturnFlag(returnFlag);
            }
            return ResponseResult.success(PageUtils.getPage(page));
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult shipmentsByOrder(SoldOrderRequestDTO soldOrderRequest) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(soldOrderRequest.getToken());
        if (null != userInfo) {
            try {
                // 发货状态
                Integer status = soldOrderRequest.getStatus();
                String allOrderStatus = null;
                Integer otherOrderStatus = null;
                if (status == 1) {

                } else if (status == 2) {
                    // 待发货
                    otherOrderStatus = 3;
                } else if (status == 3) {
                    // 已发货
                    otherOrderStatus = 4;
                } else if (status == 4) {
                    // 已完成
                    otherOrderStatus = 6;
                }
                Map<String,Object> paramMap = new HashMap<>();
                paramMap.put("shopId", userInfo.getShopId());
                paramMap.put("orderSource", soldOrderRequest.getOrderSource());
                paramMap.put("otherOrderStatus",otherOrderStatus);
                paramMap.put("userName",soldOrderRequest.getUserName());
                paramMap.put("orderNum",soldOrderRequest.getOrderNum());
                paramMap.put("orderStartTime",soldOrderRequest.getOrderStartTime());
                paramMap.put("orderEndTime",soldOrderRequest.getOrderEndTime());
                paramMap.put("page",soldOrderRequest.getPage());
                paramMap.put("limit",soldOrderRequest.getLimit());
                IPage<ShipmentsByOrderBaseVO> page = this.baseMapper.queryShipmentsOrderBase(new Query<ShipmentsByOrderBaseVO>().getPage(paramMap),paramMap);
                List<ShipmentsByOrderBaseVO> orderDetails = page.getRecords();
                for (int i = 0; i < orderDetails.size(); i++) {
                    String orderId = orderDetails.get(i).getOrderId();
                    // 退款状态
                    Integer orderRefundStatus = orderDetails.get(i).getOrderRefundStatus();
                    // 退货状态
                    Integer orderReturnStatus = orderDetails.get(i).getOrderReturnStatus();
                    // 订单状态
                    Integer normalStatus = orderDetails.get(i).getOrderStatus();
                    // 涉及退款退货订单状态
                    Integer rStatus = null;
                    if (normalStatus == 3) {
                        // 未发货状态
                        if (orderRefundStatus == 1) {
                            // 未发货退款中
                            rStatus = 22;
                        } else if (orderRefundStatus == 2) {
                            // 商家拒绝或审核通过，继续发货，但不可再次申请退款
                            rStatus = 26;
                        } else if (orderRefundStatus == 0) {
                            rStatus = 3;
                        }
                    } else if (normalStatus == 6) {
                        // 已完成状态
                        if (orderRefundStatus == 1) {
                            // 收货退款中
                            rStatus = 23;
                        } else if (orderRefundStatus == 2) {
                            rStatus = 25;
                        } else if (orderRefundStatus == 0 && orderReturnStatus == 0) {
                            rStatus = 6;
                        } else if (orderReturnStatus == 1) {
                            // 收货退货中
                            rStatus = 24;
                        } else if (orderReturnStatus == 2) {
                            rStatus = 25;
                        } else if (orderReturnStatus == 0 && orderRefundStatus == 0) {
                            rStatus = 6;
                        }
                    } else {
                        rStatus = normalStatus;
                    }
                    // 存放最新状态
                    orderDetails.get(i).setOrderStatus(rStatus);
                    List<ShipmentsByOrderGoodsDetailsVO> queryOrderDetails = orderGoodsMapper.ShipmentsByOrderGoods(orderId);
                    if (queryOrderDetails != null) {
                        orderDetails.get(i).setShipmentsByOrderGoodsDetails(queryOrderDetails);
                    }
                }
                page.setRecords(orderDetails);
                return ResponseResult.success(PageUtils.getPage(page));
            } catch (Exception e) {
                log.info("ShipmentsByOrderErrorResults:" + e.getMessage());
                return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(), BizCodeEnume.SYSTEM_ERROR.getMsg());
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(), BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
    }

    @Override
    public ResponseResult supplySoldOrders(SoldOrderRequestDTO soldOrderRequest) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(soldOrderRequest.getToken());
        if (null != userInfo) {
            try {

                Integer status = soldOrderRequest.getStatus();

                Map<String,Object> paramMap = new HashMap<>();
                paramMap.put("shopId", userInfo.getShopId());
                paramMap.put("otherOrderStatus", status);
                paramMap.put("userName", soldOrderRequest.getUserName());
                paramMap.put("orderNum", soldOrderRequest.getOrderNum());
                paramMap.put("orderStartTime", soldOrderRequest.getOrderStartTime());
                paramMap.put("orderEndTime", soldOrderRequest.getOrderEndTime());
                paramMap.put("orderType", soldOrderRequest.getOrderType());
                paramMap.put("dropShipping", soldOrderRequest.getDropShipping());
                paramMap.put("page", soldOrderRequest.getPage());
                paramMap.put("limit", soldOrderRequest.getLimit());


                IPage<OrderDetailsVO> page = this.baseMapper.querySupplyOrderBase(new Query<OrderDetailsVO>().getPage(paramMap),paramMap);
                List<OrderDetailsVO> orderDetails = page.getRecords();
                for (OrderDetailsVO vo:orderDetails){
                    String orderId = vo.getOrderId();
                    // 退款状态
                    Integer orderRefundStatus = vo.getOrderRefundStatus();
                    // 退货状态
                    Integer orderReturnStatus = vo.getOrderReturnStatus();
                    // 订单状态
                    Integer normalStatus = vo.getOrderStatus();
                    // 涉及退款退货订单状态
                    Integer Orderstatus = null;
                    if (normalStatus == 3) {
                        // 未发货状态
                        if (orderRefundStatus == 1) {
                            // 未发货退款中
                            Orderstatus = 22;
                        } else if (orderRefundStatus == 2) {
                            // 商家拒绝或审核通过，继续发货，但不可再次申请退款
                            Orderstatus = 26;
                        } else if (orderRefundStatus == 0) {
                            Orderstatus = 3;
                        }
                    } else if (normalStatus == 6) {
                        // 已完成状态
                        if (orderRefundStatus == 1) {
                            // 收货退款中
                            Orderstatus = 23;

                        } else if (orderRefundStatus == 2) {
                            Orderstatus = 25;

                        } else if (orderRefundStatus == 0 && orderReturnStatus == 0) {
                            Orderstatus = 6;
                        } else if (orderReturnStatus == 1) {
                            // 收货退货中
                            Orderstatus = 24;

                        } else if (orderReturnStatus == 2) {
                            Orderstatus = 25;

                        } else if (orderReturnStatus == 0 && orderRefundStatus == 0) {
                            Orderstatus = 6;
                        }
                    } else {
                        Orderstatus = normalStatus;
                    }
                    // 存放最新状态
                    vo.setOrderStatus(Orderstatus);
//                    if(vo.getDistributionDiscount() != null && vo.getDistributionDiscount().compareTo(BigDecimal.ZERO) > 0){
//                        BigDecimal discount = vo.getOrderGoodsAmount().multiply(vo.getDistributionDiscount().multiply(BigDecimal.valueOf(0.01)));
//                        vo.setDistributionDiscount(discount);
//                    }
                    List<GoodsDetailsVO> queryOrderDetails = orderGoodsMapper.querySupplyOrders(orderId);
                    if (queryOrderDetails != null) {
                        for (GoodsDetailsVO queryOrderDetail : queryOrderDetails) {
                            queryOrderDetail.setSupperGoodsPrice(queryOrderDetail.getOrderGoodsAmount().divide(BigDecimal.valueOf(queryOrderDetail.getOrderGoodsNum()),2, RoundingMode.HALF_UP));
                        }
                        vo.setGoodsDetails(queryOrderDetails);
                    }
                }
                return ResponseResult.success(PageUtils.getPage(page));
            } catch (Exception e) {
                e.printStackTrace();
                log.info("SoldOrdersErrorResults:" + e.getMessage());
                return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
    }

    public void plusdis(String orderId,String userId,List goodsId) throws ParseException {
        //退还该订单plus折扣额度
        Map map1 = orderCommissionMapper.selectplusdis(orderId,goodsId);
        String goodsPlusDiscount = String.valueOf(map1.get("goods_plus_discount"));
        goodsPlusDiscount = goodsPlusDiscount == "null" ? "0" : goodsPlusDiscount;
        BigDecimal bigDecimal = new BigDecimal(goodsPlusDiscount);

        //下单时间
        Date createTime = DateUtils.parseCNDate(map1.get("order_goods_time").toString());
        //查看会员是否过期
        PlusMemberEntityVO plusMemberEntity = this.baseMapper.selectplusmember(userId);
        if (plusMemberEntity != null){
            DateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
            //已用额度
            BigDecimal usedAmount = plusMemberEntity.getUsedAmount();

            Date star = dft.parse(dft.format(plusMemberEntity.getThaliStarttime()));//任务执行时间

            Date endDay = dft.parse(dft.format(new Date()));
            //当前时间与其他时间相差的毫秒数
            Long diff = endDay.getTime() - star.getTime();
            BigDecimal divide = BigDecimal.valueOf(diff).divide
                    (BigDecimal.valueOf(60 * 60 * 1000 * 24), 2, BigDecimal.ROUND_HALF_UP);
            int value = divide.divide(BigDecimal.valueOf(30), 2, BigDecimal.ROUND_HALF_UP).intValue();
            //计算订单是否用返回折扣
            //开始时间
            Calendar instance = Calendar.getInstance();
            instance.setTime(plusMemberEntity.getThaliStarttime());
            instance.add(Calendar.DATE,30 * value);
            //开始时间
            Date starttime = instance.getTime();
            instance.add(Calendar.DATE,30);
            //结束时间
            Date endtime = instance.getTime();

            boolean b = DateUtils.belongCalendar(createTime, starttime, endtime);
            if (b){
                //在时间段  退还plus会员折扣
                this.baseMapper.updateplusmember(userId,bigDecimal);
            }
        }
    }

}
